简体   繁体   English

StructLayout Pack = 1不适用于bool?

[英]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: 所以我有两个问题:

  • Why does marshalling work this way? 为什么编组以这种方式工作?
  • Any workaround? 任何解决方法? I have 1-byte booleans in native structs I need to import. 我需要导入本机结构中的1字节布尔值。 I can use byte instead of course but it's "messy". 我可以使用字节而不是当然,但它是“凌乱”。

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 BOOLtypedef ED作为int为好),因此它转换为4个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM