在c++项目cpptest.dll中定义: struct A { int X; int Y; };
extern "C" __declspec(dllexport) int fun1(A *a);
int fun1(A *a) { return a->X; }
在C#项目中定义: [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] class A { public int X; public int Y; }
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int dofun(ref A a1);
class Program
{
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 = 1;
a1.Y = 2;
Console.WriteLine(dofun1(ref a1));
}
}
为什么每次运行输出都不相同,且数字不是1也不是2,而是类似7825552,14052168,21507032?该如何修改呢?
class A换成struct A