How does packaging work when sorting?

I have this structure:

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

and then I ran this command to get the size:

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

and the answer is consistent

Marshal.SizeOf(typeof(MyStruct_t))= 36 

I was expecting 40. Am I missing something? Is there something I don’t understand in the meaning of Pack = 8?

+4
source share
1 answer

From MSDN :

Type instance fields are aligned using the following rules:

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

You have Pack=8, but your largest size is 4 ( UInt32). Less than 8 and 4 is 4.

If you want your structure to be 40 bytes, you need to add 4 bytes of "padding".

+4
source

Source: https://habr.com/ru/post/1695156/


All Articles