不同的bool大小

时间:2012-11-08 09:17:02

标签: c# boolean marshalling

  

可能重复:
  Marshal.SizeOf structure returns excessive number

正如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

2 个答案:

答案 0 :(得分:1)

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

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

大概是Marshal假设每个字段对齐4个字节。

答案 1 :(得分:1)

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

exmaples:

[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