I am attempting to marshal a byte array as a struct in C#. I believe that I am running into an issue regarding how my struct is being packed/padded that is resulting in some unexpected results. For example, I have the following byte array:
byte[] bytes = { 0x07, 0x01, 0x01, 0x01, 0x00, 0xb6, 0xa6, 0xb8, 0x00, 0x90, 0x00, 0x00 };
And am trying to to marshal as my struct:
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct mystruct
{
[MarshalAs(UnmanagedType.I1)]
public byte a;
[MarshalAs(UnmanagedType.I1)]
public byte b;
[MarshalAs(UnmanagedType.I1)]
public byte c;
[MarshalAs(UnmanagedType.I1)]
public byte d;
[MarshalAs(UnmanagedType.U4)]
public uint e;
[MarshalAs(UnmanagedType.U2)]
public ushort f;
[MarshalAs(UnmanagedType.I1)]
public byte g;
[MarshalAs(UnmanagedType.I1)]
public byte h;
}
With this code:
GCHandle gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
mystruct output = (mystruct)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(mystruct));
However, the byte offsets are always wrong following the 4 byte uint, no matter what I have tried in regard to specifying the StructLayout. E.g. where I would expect mystruct.f = 0x0090 = 144
, I am getting mystruct.f = 0x9000 = 36864
What am I doing wrong here? Should I be taking a different approach? Is it not possible to pack the struct in such a way that no additional padding is added?