【发布时间】:2016-01-07 05:20:05
【问题描述】:
在进行P/Invoke时,数据布局匹配很重要。
我们可以通过一些属性来控制结构体的布局。
例如:
struct MyStruct
{
public bool f;
}
大小为 4。虽然我们可以告诉编译器将其设为 1 字节布尔值以匹配 bool 的 C++ 类型:
struct MyStruct
{
[MarshalAs(UnmanagedType.I1)]
public bool f;
}
大小为 1。
这些是有道理的。但是当我测试固定的布尔数组时,我很困惑。
unsafe struct MyStruct
{
public fixed bool fs[1];
}
给出 4 个字节的大小。和
unsafe struct MyStruct
{
public fixed bool fs[4];
}
仍然给出 4 个字节的大小。但是
unsafe struct MyStruct
{
public fixed bool fs[5];
}
大小为 8。
看起来在固定的bool数组中,bool元素的大小仍然是1字节,但对齐是4字节。这与 1 字节大小和对齐的 C++ bool 数组不匹配。
有人可以解释一下吗?
更新:我终于发现,原因是结构中的 bool 类型,那么该结构将永远不会是 blittable!所以不要期望内部具有 bool 类型的结构与 C 中的布局相同。
问候, 向。
【问题讨论】: