gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:03:52 25 4
gpt4 key购买 nike

我尝试在 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();

如果我运行带有以下消息的代码,它会失败:(已翻译)

{"The Type "Union" of the Assembly [...] could not be loaded because it contained an Objectfield at Offset 0, which is not aligned correctly or got overlapped by a field which isnt a ObjectField":"Union"}

有什么建议吗?

Ps:原始代码已大大简化以仅显示问题。 Struct多了很多,Union也被另一个Struct包含了。

最佳答案

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
}

关于c# - Marshal Union(C ) 与结构包含 C# 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11243142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com