C#中的联盟:结构成员似乎不对齐

时间:2012-12-24 18:14:17

标签: c# struct unions

我已经定义了以下结构来模拟C ++联合(最终将用于C ++ Interop):

[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?所有结构成员IMO似乎都是一致的。

1 个答案:

答案 0 :(得分:9)

LayoutKind.Sequential仅影响此结构的非托管表示。这是因为结构包含非blittable类型(即字符串) 如果只有blittable typesLayoutKind.Sequential将控制托管和非托管代表(reference)。

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

您可以在LayoutKind.ExplicitSTRUCT1中使用STRUCT2来解决此问题,因为Explicit会影响blittable和非blittable类型的托管和非托管表示。< / p>

相关问题