私はC++で以下を持っています:
struct TestA {
int i;
char text[512];
};
struct TestB {
double n;
char text[512];
};
union TestUnion {
struct TestA a;
struct TestB b;
};
int fnUnmanagedDLL(int which,TestUnion *);
次のように C# ラッパーを宣言してみました。
public class WrapperClass
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TestA
{
public int i;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 512)]
public string text;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct TestB
{
public double n;
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 512)]
public string text;
}
[StructLayout(LayoutKind.Explicit)]
public struct TestUnion
{
[FieldOffset(0)]
public TestA a;
[FieldOffset(0)]
public TestB b;
}
[DllImport("UnmanagedDLL.Dll")]
public static extern int fnUnmanagedDLL(int which,ref TestUnion obj);
}
WrapperClass.TestUnion を参照するプログラムを実行するとすぐに、「オフセットにオブジェクト フィールドが含まれているため、アセンブリ 'UnmanagedToManaged、Version=1.0.0.0、Culture=neutral、PublicKeyToken=null' からタイプ 'TestUnion' をロードできませんでした' が表示されます。 0 が正しく整列されていないか、オブジェクト以外のフィールドと重なっています。".
これは単なるテストプログラムです。ユニオンを削除するための別の質問で提案を見ました。ただし、事前に DLL によってどの構造が埋められるかはわかりません。私が間違っていることについて誰かがアドバイスを提供できますか?