Marshal Union(C)的结构包含C#中的数组

时间:2012-06-28 10:57:51

标签: c# arrays struct union marshalling

我尝试在c#中编组一个非托管的c ++ dll,但是在创建联合时marshaller失败了。

为什么这段代码失败了?

    [StructLayout(LayoutKind.Sequential)]
    public struct StructWithArray
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public int[] MySimpleArray;
        //More Stuff
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct Union
    {
        [FieldOffset(0)]
        public int Int; //Or anything else
        [FieldOffset(0), MarshalAs(UnmanagedType.Struct)]
        public StructWithArray MyStructWithArray;
        //More Structs
    }

然后构建联盟:

Union MyUnion = new Union();

如果我使用以下消息运行代码,则会失败:(已翻译)

  

{“无法加载程序集[...]的Type”Union“,因为它包含Offset 0处的Objectfield,它没有正确对齐或被一个不是ObjectField的字段重叠”:“Union “}

任何建议?

Ps:原始代码大大简化,仅显示问题。还有更多的Structs,而Union也被另一个Struct包含。

1 个答案:

答案 0 :(得分:0)

MySimpleArray声明为固定的不安全数组:

[StructLayout(LayoutKind.Sequential)]
public unsafe struct StructWithArray
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
    public fixed int MySimpleArray[2];
    //More Stuff
}

[StructLayout(LayoutKind.Explicit)]
public struct Union
{
    [FieldOffset(0)]
    public int Int; //Or anything else
    [FieldOffset(0), MarshalAs(UnmanagedType.Struct)]
    public StructWithArray MyStructWithArray;
    //More Structs
}