编组时打包如何工作?

How does packing work when marshalling?

我有这样的结构:

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

然后我运行这个命令来获取尺寸:

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

答案始终如一

Marshal.SizeOf(typeof(MyStruct_t))= 36 

我本以为是 40 岁。我错过了什么吗? Pack=8 的含义有什么我不明白的地方吗?

来自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.

您有一个 Pack=8,但您的最大尺寸元素是 4(UInt32)。 8 和 4 中较小的一个是 4.

如果您希望您的结构为 40 字节,则必须添加 4 个字节的 "padding"。