简体   繁体   中英

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?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM