C# 中的联合:结构成员似乎没有对齐

2023-12-24

我定义了以下结构来模拟 C++ 联合(最终将用于 C++ 互操作):

[StructLayout(LayoutKind.Sequential)]
internal struct STRUCT1
{
    public Guid guid;

    public String str1;
    public String str2;
}

[StructLayout(LayoutKind.Sequential)]
internal struct STRUCT2
{
    public Guid guid;

    public String str1;
    public String str2;

    public Int32 i1;
}

[StructLayout(LayoutKind.Explicit)]
internal struct MASTER_STRUCT_UNION
{
    [FieldOffset(0)]
    public STRUCT1 Struct1;

    [FieldOffset(0)]
    public STRUCT2 Struct2;
}

[StructLayout(LayoutKind.Sequential)]
internal struct MASTER_STRUCT
{
    public MASTER_STRUCT_UNION Union;
}

我编写了以下测试代码,该代码将值分配给Struct1.guid并测试是否相等Struct2.guid:

class Class1
{
    public static void Test()
    {
        MASTER_STRUCT ms = new MASTER_STRUCT();

        bool match;
        ms.Union.Struct1.guid = new Guid(0xffeeddcc, 0xbbaa, 0x9988, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0);

        Console.WriteLine("Struct1.guid:\t\t{0}\n", ms.Union.Struct1.guid.ToString());

        Console.WriteLine("Struct2.integer:\t{0:x}", ms.Union.Struct2.i1);
        Console.WriteLine("Struct2.guid:\t\t{0}", ms.Union.Struct2.guid.ToString());


        match = ms.Union.Struct1.guid == ms.Union.Struct2.guid ? true : false;
    }
}  

为什么Struct2.guid不等于Struct1.guid而是一段Struct2.guid的值似乎转变为Struct2.integer?在我看来,所有结构成员似乎都是一致的。


The LayoutKind.Sequential只影响该结构的非托管表示。这是因为该结构包含不可直接复制的类型(即字符串)。
要是可直接传送的类型 http://msdn.microsoft.com/en-us/library/75dwhxf7.aspx在场,LayoutKind.Sequential将控制托管和非托管表示(参考 http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx).

在您的情况下,编译器决定将整数放在托管表示中的两个字符串之前(您可以看到,如果将鼠标悬停在ms在调试和展开时STRUCT2).

您可以使用以下方法修复该问题LayoutKind.Explicit同时STRUCT1 and STRUCT2, 因为Explicit影响 blittable 和 nonblittable 类型的托管和非托管表示。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 中的联合:结构成员似乎没有对齐 的相关文章

随机推荐