簡體   English   中英

StructLayout Pack = 1不適用於bool?

[英]StructLayout Pack=1 doesn't work with bool?

測驗:以下程序打印什么?

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和byte都有1個字節的大小,指定[StructLayout(LayoutKind.Sequential, Pack=1)]應該使任何填充問題無效。 兩個結構都應該是5個字節。 所以我有兩個問題:

  • 為什么編組以這種方式工作?
  • 任何解決方法? 我需要導入本機結構中的1字節布爾值。 我可以使用字節而不是當然,但它是“凌亂”。

謝謝。

默認情況下,.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

bool被鎧到int32 ,互操作性的原因(C / C ++程序通常使用int為布爾值和在WINAPI BOOLtypedef ED作為int為好),因此它轉換為4個字節。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM