VS10下调用dll,代码如下:
// C++接口声明 void test(char *str); // 接口声明 [DllImport("datalib.dll", EntryPoint = "test")] public static extern void test(string str); // 调用 string str="Hello"; test(str);
运行出现异常: 调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。
出现这个错误,可能
1.参数类型不匹配
难道char*不能用string来表示,IntPtr是一定可以的.将C++类型更改成int类型后测试,发现仍然出错,这样看来,不可能是参数类型不匹配了
2. 调用约定不匹配
DllImport还有一个CallingConvention的属性,默认值是CallingCovention.Stdcall, 此处更改成Cdecl(c/c++默认调用方式)就可以了
[DllImport("datalib.dll", EntryPoint = "test",CallingConvention=CallingConvention.Cdecl)] public static extern void test(string str);
VS10下必须得指定这个属性才能运行, 同样的代码在VS08下却不存在这样的问题, 奇怪 ...