1

I am having "Incorrectly aligned or overlapped by non-object field" error with the following code.

public struct TypeA
{
   public string A1;
   public string A2;
}
public struct TypeB
{
   public string B1,
   public string B2;
}

I implemented union by using System.Runtime.InteropServices with LayoutKind.Explicit

[StructLayout(LayoutKind.Explicit)]
public struct TypeAorB
{
   [FieldOffset(0)]
   public TypeA aa;

   [FieldOffset(0)]
   public TypeB bb;
}

I think the issue comes from string in the struct. How do I overcome this problem?

4

2 回答 2

2

你试图做的事情是不合法的。String 是一种引用类型,不能与联合中的任何其他内容重叠。这对垃圾收集器来说非常重要,它无法可靠地确定字段中存储了哪些引用,因此它无法可靠地确定字符串对象是否需要保持活动状态。

您的结构的奇怪之处在于您将字符串与字符串重叠。这在技术上可行,垃圾收集器没有理由感到困惑,因为它总是看到一个有效的对象引用。但它实际上并没有处理这种特殊情况,微软没有编写足够的代码,也没有关心消耗 cpu 周期来检查类型标识。

这是有充分理由的,因为不必在声明中重叠它们。当您可以轻松避免重叠时,Microsoft 没有必要编写特殊代码来识别重叠。

在您的示例中,海龟一直向下,联合的每个领域都是相同的。所以使用联合没有任何意义。

所以不要。

于 2014-02-10T23:38:17.683 回答
-2

Why are the fieldoffsets the same? They should be 0 and 0+[size of TypeA].

Type A is 8 bytes as you have 2x strings, and each one will use a 4 byte pointer.

Therefore...

    [StructLayout(LayoutKind.Explicit)]
    public struct TypeAorB
    {
        [FieldOffset(0)]
        public TypeA aa;

        [FieldOffset(8)]
        public TypeB bb;
    }

If you were to add a third field of typeB again, you'd need to do:

    [StructLayout(LayoutKind.Explicit)]
    public struct TypeAorB
    {
        [FieldOffset(0)]
        public TypeA aa;

        [FieldOffset(8)]
        public TypeB bb;

        [FieldOffset(16)]
        public TypeB bb;
    }
于 2014-02-10T23:24:02.957 回答