I have following code
static byte[] testBytes2 = { 49, 56, 58, 0, 123, 0, 0, 0, 1, 1, 1 };
[StructLayout(LayoutKind.Explicit, Pack = 1)]
internal unsafe struct fields_test
{
[FieldOffset(0)]
public fixed byte a0[4];
[FieldOffset(4)]
public System.UInt32 a1;
//[FieldOffset(8)] // if you uncomment these lines variable a0 will not be filled!! only one byte will be copied!
//public System.Boolean a2;
};
GCHandle handle = GCHandle.Alloc(testBytes2, GCHandleType.Pinned);
fields_test test = (fields_test)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(fields_test));
handle.Free();When you run it, bytes will be copied to structure correctly. BUT. If you uncomment last 2 lines, essentially adding one Boolean in the end of struct, first byte[] will not be filled with values anymore!!! only one byte will be copied!!
This seems like a bug inside PtrToStructure function !!!
here is result of first run:
test.a0 == [49,56,58,0 ]
test.a1 == 123
here is result of second run:
test.a0 == [49,0,0,0 ]
test.a1 == 123
test.a2 == True