2
我有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:
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#包裝這樣的,我得到「無法從程序集'UnmanagedToManaged,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'加載類型'TestUnion',因爲它包含偏移量爲0的對象字段,該對象字段被非對象錯誤地對齊或重疊領域。」。
這只是一個測試程序。在另一個問題中,我確實看到了關於刪除這個選項的建議。但是,我不知道哪個結構會被DLL預先填充。任何人都可以提供關於我在做什麼錯誤的建議嗎?
謝謝你提供的信息。對於其他讀者來說,有幾個錯別字: –
緩衝區大小隻有四個字節。那麼,有沒有辦法來解釋字符串?另外,如果一個結構有雙重結構,我預計它會更大。 –