Search code examples
c#marshalling

How does packing work when marshalling?


I have this structure:

[StructLayout(LayoutKind.Sequential, Pack = 8)]
unsafe struct MyStruct_t
{
    public UInt32 ulID;
    public fixed Byte xValue[32];
}

and then i run this command to get the size:

Console.WriteLine("Marshal.SizeOf(typeof(MyStruct_t))= {0}", Marshal.SizeOf(typeof(MyStruct_t)));

and the answer is consistently

Marshal.SizeOf(typeof(MyStruct_t))= 36 

I was expecting 40. Am i missing something? Is there something i do not understand in the meaning of Pack=8?


Solution

  • From MSDN:

    The fields of a type instance are aligned by using the following rules:

    • The alignment of the type is the size of its largest element (1, 2, 4, 8, etc., bytes) or the specified packing size, whichever is smaller.

    You have a Pack=8, but your largest size element is 4 (the UInt32). The lesser of 8 and 4 is 4.

    If you want your struct to be 40 bytes, you'll have to add 4 bytes of "padding".