[英]StructLayout Pack=1 doesn't work with bool?
Quiz: what does the following program print? 测验:以下程序打印什么?
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();
}
}
}
Answer: 回答:
8
5
This is very confusing to me. 这对我来说非常困惑。 Both bool and byte have a size of 1 byte, and specifying [StructLayout(LayoutKind.Sequential, Pack=1)]
should nullify any padding issues. bool和byte都有1个字节的大小,指定[StructLayout(LayoutKind.Sequential, Pack=1)]
应该使任何填充问题无效。 Both structs should be 5 bytes. 两个结构都应该是5个字节。 So I have two questions: 所以我有两个问题:
Thanks. 谢谢。
By default, .NET type bool
marshals to unmanaged type BOOL
, which is typedef
ed to int
. 默认情况下,.NET类型bool
乘警非托管类型BOOL
,这是typedef
版来int
。 If you want to marshal to and from 1-byte unmanaged booleans, indicate this to the marshaler with an attribute: 如果要对1字节非托管布尔值进行编组,请使用属性向封送器指示:
[StructLayout (LayoutKind.Sequential, Pack=1)]
struct Struct3 {
[MarshalAs (UnmanagedType.I1)]
bool b;
int i;
}
Console.WriteLine (Marshal.SizeOf (typeof (Struct3))) ; // prints 5
bool
被铠到int32
,互操作性的原因(C / C ++程序通常使用int
为布尔值和在WINAPI BOOL
被typedef
ED作为int
为好),因此它转换为4个字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.