1

可能重复:
Marshal.SizeOf 结构返回过多的数字

正如MSDN所说,这sizeof(bool)1个字节。但是当我将 bool 放入 struct 时,sizeof struct 变为4字节。有人可以解释这种行为吗?

[StructLayout(LayoutKind.Sequential)]
public struct Sample1
{
    public bool a1;
}

int size1 = Marshal.SizeOf(typeof (Sample1));  // 4
int size2 = sizeof (bool);                     // 1
4

2 回答 2

1

您不能直接比较sizeofMarshal.SizeOf。例如,如果我们以相同的方式测量它,我们会得到相同的结果:

static unsafe void Main() { // unsafe is needed to use sizeof here
    int size1 = sizeof(Sample1); // 1
}

据推测Marshal假设每个字段对齐 4 个字节。

于 2012-11-08T09:22:41.423 回答
1

当使用结构/类时,大小总是与特定大小对齐,在每个架构上它可能不同,但通常是 4,所以如果你在 bool 之后有 int,我们从 4 的乘法开始,导致处理器读取 4 个字节块。
这是在设置类(或结构)中成员的顺序时值得考虑的事情

示例:

[StructLayout(LayoutKind.Sequential)]
public struct Sample1
{
    public bool a1;//take 1 byte but align to 4
}
public struct Sample2
{
    public bool a1;//take 1 byte but align to 4
    public int  a2;//take 4 bytes (32bit machine) start at a multiplication of 4
    public bool a3;//take 1 byte but align to 4
}
public struct Sample3
{
    //here the compiler (with the right optimizations) can put all the bools one after the other without breaking the alignment
    public bool a1;
    public bool a2;
    public bool a3;
    public bool a4;
    public int  a5;
}
int size1 = Marshal.SizeOf(typeof (Sample1));  // 4
int size1 = Marshal.SizeOf(typeof (Sample2));  // 12
int size1 = Marshal.SizeOf(typeof (Sample3));  // 8
int size2 = sizeof (bool);                     // 1 
于 2012-11-08T09:29:06.267 回答