【问题标题】:Different bool size [duplicate]不同的布尔大小[重复]
【发布时间】:2012-11-08 09:17:02
【问题描述】:

可能重复:
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

【问题讨论】:

  • Marshal.SizeOf 正在测量与sizeof 非常不同 的东西...
  • 这可能与对齐有关。您是否尝试将 Pack=1 添加到 StructLayout 属性的构造函数?
  • @Botz3000,edze,Rawling - 尝试使用 Pack=1,结果相同

标签: c# boolean marshalling


【解决方案1】:

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

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

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

【讨论】:

  • 所以这意味着当用 bool 字段编组 c++ struct 时,我不能在 C# struct 中使用 bool 字段?那我应该用什么类型的?字节?
  • @Stecya 我希望字节对齐相同;但是,在不同的情况下使用不同的方法。它已经可以正常工作
  • 当 bool field marshal 没有正确转换 struct 时,将其更改为 byte 并得到正确的结果。只是好奇它为什么会这样
【解决方案2】:

当使用结构/类时,大小总是与特定大小对齐,在每个架构上它可能不同,但通常是 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 

【讨论】:

  • 我实际上在你的代码 sn-p 中得到了 Sample3 的不同结果,它是 20
  • @Stecya - 当我说“编译器知道”时,它实际上取决于您为编译定义的优化设置。我使用我的定义来输入数字(:。我已将答案固定为更具解释性。
  • 好的,我在 Sample1 中将 bool 更改为 byte 并得到 1 个字节,所以它显然没有对齐问题
猜你喜欢
  • 2016-04-02
  • 2016-08-16
  • 2012-12-15
  • 2015-09-19
  • 2014-04-08
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多