簡體   English   中英

Marshal Union(C)的結構包含C#中的數組

[英]Marshal Union(C ) with a Struct which contains an Array in C#

我嘗試在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();

如果我使用以下消息運行代碼,它將失敗:(已翻譯)

無法加載{“The Type”Union of the Assembly [...],因為它包含Offset 0處的Objectfield,它沒有正確對齊或被一個不是ObjectField的字段重疊“:”Union“}

有什么建議?

Ps:原始代碼大大簡化,只顯示問題。 還有更多的結構,聯盟也包含在另一個結構中。

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
}

暫無
暫無

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

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