[英]Convert C++ union of structs to C#
我正在嘗試使用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]在struct 字段上很好。 但是你的聲明只有嵌套類型(請注意,在C ++代碼中,結構實際上是匿名的,但用於聲明一個新字段......你的C#代碼只聲明一個命名結構,但沒有實際字段)。 請注意,您還需要包含[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;
}
你當然可以使用FieldOffset
,這就是答案。 但是你需要將聯合定義為一種獨特的類型。
以通常的方式定義每個結構。 我假設你知道怎么做。
然后定義聯合:
[StructLayout(LayoutKind.Explicit)]
public struct MyUnion
{
[FieldOffset(0)]
public FirstStruct firststruct;
[FieldOffset(0)]
public SecondStruct secondstruct;
[FieldOffset(0)]
public ThirdStruct thirdstruct;
}
最后把它們放在一起:
[StructLayout(LayoutKind.Sequential)]
public struct OuterStruct
{
public int outervar;
public int othervar;
public MyUnion myunion;
}
關鍵是始終使聯合成為一種獨特的類型,並為每個成員使用零偏移量。
FWIW,C ++ long
在Windows上是32位有符號整數。 這是C#中的int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.