Marshal.PtrToStructure (and back again) and generic solution for endianness swapping

后端 未结 4 1880
情书的邮戳
情书的邮戳 2020-12-02 15:02

I have a system where a remote agent sends serialized structures (from an embedded C system) for me to read and store via IP/UDP. In some cases I need to send back the same

4条回答
  •  -上瘾入骨i
    2020-12-02 15:27

    For those of us without Linq, a replacement RespectEndianness():

    private static void RespectEndianness(Type type, byte[] data) {
        foreach (FieldInfo f in type.GetFields()) {
            if (f.IsDefined(typeof(EndianAttribute), false)) {
                EndianAttribute att = (EndianAttribute)f.GetCustomAttributes(typeof(EndianAttribute), false)[0];
                int offset = Marshal.OffsetOf(type, f.Name).ToInt32();
                if ((att.Endianness == Endianness.BigEndian && BitConverter.IsLittleEndian) ||
                    (att.Endianness == Endianness.LittleEndian && !BitConverter.IsLittleEndian)) {
                    Array.Reverse(data, offset, Marshal.SizeOf(f.FieldType));
                }
            }
        }
    }
    

提交回复
热议问题