我不是 COM 或 C++/C# 编码(marshal)处理方面的专家,在这种情况下需要一些帮助:
native 代码:
typedef struct _Foo {
FooType a; // enum
WCHAR b[16];
WCHAR c[16];
BOOL d;
ULONG size;
} Foo;
typedef struct _Bar {
GUID a;
WCHAR b[16];
WCHAR c[16];
BOOL d;
} Bar;
typedef struct _Baz {
FILETIME a;
FILETIME b;
ULONG c;
ULONG d;
GUID e;
} Baz;
typedef struct _FooBarBaz
{
SomeType type; // enum
[switch_is(type)] union
{
[case(SomeType.A)]
Foo a;
[case(SomeType.B)]
Bar b;
[case(SomeType.C)]
Baz b;
} data;
} FooBarBaz;
托管代码:
[StructLayout(LayoutKind.Sequential)]
internal struct Foo
{
public FooType a;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] b;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] c;
[MarshalAs(UnmanagedType.Bool)]
public bool d;
[MarshalAs(UnmanagedType.U4)]
public uint e;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Bar
{
public Guid a;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] b;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public char[] c;
[MarshalAs(UnmanagedType.Bool)]
public bool d;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Baz
{
public ComTypes.FILETIME a;
public ComTypes.FILETIME b;
[MarshalAs(UnmanagedType.U4)]
public uint c;
[MarshalAs(UnmanagedType.U4)]
public uint d;
public Guid e;
}
internal struct FooBarBaz
{
public SomeType Type;
// ??????
}
我不确定如何将 native 结构 FooBarBaz 转换/编码为托管代码。如有任何提示,我们将不胜感激。
最佳答案
关于翻译的宝贵资源可以找到here IMO,每一页都值得阅读 :)
关于FooBarZ,你要找的是[FieldOffset(NBR)],就是翻译union的方式。
看the translation in pinvoke的 STRRET struct有关如何使用它的示例。
关于c# - 使用结构 union 将 C++ 编码到 C# 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17737088/