小测验:下面的程序打印什么?
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication2 {
[StructLayout(LayoutKind.Sequential, Pack=1)]
struct Struct1 {
bool b;
int i;
}
[StructLayout(LayoutKind.Sequential, Pack=1)]
struct Struct2 {
byte b;
int i;
}
class Program {
static void Main(string[] args) {
Console.WriteLine(Marshal.SizeOf(typeof(Struct1)));
Console.WriteLine(Marshal.SizeOf(typeof(Struct2)));
Console.ReadKey();
}
}
}答案:
8
5这让我很困惑。bool和[StructLayout(LayoutKind.Sequential, Pack=1)]的大小都是1字节,指定可以消除任何填充问题。这两个结构都应该是5个字节。所以我有两个问题:
谢谢。
发布于 2012-03-19 07:31:24
默认情况下,.NET类型bool封送到非托管类型BOOL,后者由typedef编辑为int。如果要封送1字节的非托管布尔值,请向具有属性的封送处理程序指示如下:
[StructLayout (LayoutKind.Sequential, Pack=1)]
struct Struct3 {
[MarshalAs (UnmanagedType.I1)]
bool b;
int i;
}
Console.WriteLine (Marshal.SizeOf (typeof (Struct3))) ; // prints 5发布于 2012-03-19 07:31:40
由于互操作性的原因,bool被编组到int32中(C/C++程序通常使用int作为布尔,而在winapi中,BOOL也是typedef编辑的int ),因此它被转换为4字节。
https://stackoverflow.com/questions/9766403
复制相似问题