在c++項目cpptest.dll中定義:
struct A
{
int X;
int Y;
A *a;
};
extern "C" __declspec(dllexport) int fun1(A *a);
在C#項目TestDll.exe中定義:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
class A
{
public int X;
public int Y;
public A a;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int dofun(ref A a1);
然後調用
public static class NativeMethod
{
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
public static extern int LoadLibrary(
[MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
public static extern IntPtr GetProcAddress(int hModule,
[MarshalAs(UnmanagedType.LPStr)] string lpProcName);
}
static void Main(string[] args)
{
//1. 動態加載C++ Dll
int hModule = NativeMethod.LoadLibrary("cpptest.dll");
if (hModule == 0) return;
//2. 讀取函數指針
IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "fun1");
//3. 將函數指針封裝成委托
dofun dofun1 = (dofun)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(dofun));
A a1 = new A();
a1.X = 100;
a1.Y = 20;
A a2 = new A();
a1.a = a2;
Console.WriteLine(dofun1(ref a1));
}
結果報錯:“System.TypeLoadException”類型的未經處理的異常在TestDll.exe中發生。其他信息:無法封送處理類型為“TestDll.A”的字段“a”: 該類型不支持封送處理。
這個問題如何解決?請求高手急救,不勝感激!!
C#這裡
class A換成struct A