Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用包含C中数组的结构封送联合(C)#_C#_Arrays_Struct_Union_Marshalling - Fatal编程技术网

C# 使用包含C中数组的结构封送联合(C)#

C# 使用包含C中数组的结构封送联合(C)#,c#,arrays,struct,union,marshalling,C#,Arrays,Struct,Union,Marshalling,我试图在C语言中封送一个非托管C++ DLL,但是封送器在创建我的联合时失败了。 为什么这个代码会失败 [StructLayout(LayoutKind.Sequential)] public struct StructWithArray { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public int[] MySimpleArray; //More Stuf

我试图在C语言中封送一个非托管C++ DLL,但是封送器在创建我的联合时失败了。 为什么这个代码会失败

    [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();
如果我使用以下消息运行代码,它将失败:(已翻译)

{“未能加载程序集[…]的类型“Union”,因为它在偏移量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
}

可能是包装问题。尝试首先将属性Pack=4添加到第一个结构中。你的头文件中有那些结构的#pragma包吗?我的头文件中没有#pragma。在这段代码中,我甚至没有加载dll。这个例子足以得到错误。Pack=1,Pack=4测试,固定大小测试,将数组直接复制到联合测试中,所有结果都是一样的。看到这一点,您的解决方案似乎是用[StructLayout(LayoutKind.Sequential)]公共结构StructWithArray{int a;int b;//More Stuff}替换第一个结构。是的,我认为这是唯一的解决方法。或者对于本机结构,我可以使用“不安全”和“固定数组”,但正如我所说,这只适用于int、uint等本机结构。遗憾的是,“固定”关键字只适用于int、bytes等值类型。假设我有一个其他结构的数组,“固定”关键字不再起作用。