我正在尝试使用 C# 来使用 C++ 库,该库包含一个记录为如下布局的结构:
struct {
long outervar;
long othervar;
union {
struct {
long a;
} firststruct;
struct {
long p;
long q;
long r;
long s;
} secondstruct;
struct {
long x;
long y;
long z;
} thirdstruct;
} myunion;
} outerstruct;
理想情况下我想实现这样的东西:
struct outerstruct
{
UInt32 outervar;
UInt32 othervar;
[FieldOffset(0)]
struct firststruct
{
UInt32 a;
}
[FieldOffset(0)]
struct secondstruct
{
UInt32 p;
UInt32 q;
UInt32 r;
UInt32 s;
}
[FieldOffset(0)]
struct thirdstruct
{
UInt32 x;
UInt32 y;
UInt32 z;
}
}
当然,我不能在结构上使用 FieldOffset 或 MarshalAs,但我不知道如何实现它。如果有人对如何在 C# 中实现这一点有一些想法,我将不胜感激。
谢谢!
最佳答案
[FieldOffset] 在结构字段上很好。但是您的声明只有嵌套类型(请注意,在 C++ 代码中,结构实际上是匿名的,但用于声明新字段...您的 C# 代码仅声明一个命名 结构,但没有实际的 field )。请注意,您还需要包含 [StructLayout(LayoutKind.Explicit)],并为结构中的所有字段提供偏移量。
尝试这样的事情:
struct firststruct
{
UInt32 a;
}
struct secondstruct
{
UInt32 p;
UInt32 q;
UInt32 r;
UInt32 s;
}
struct thirdstruct
{
UInt32 x;
UInt32 y;
UInt32 z;
}
[StructLayout(LayoutKind.Explicit)]
struct union
{
[FieldOffset(0)]
firststruct firststruct;
[FieldOffset(0)]
secondstruct secondstruct;
[FieldOffset(0)]
thirdstruct thirdstruct;
}
struct outerstruct
{
UInt32 outervar;
UInt32 othervar;
union union;
}
关于c# - 将 C++ 结构体 union 转换为 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26390414/