P/Invoke, c++参数是char*, c#用string传入,debug时报错,直接运行却不报错???
c++函数:
C/C++ code
extern "C" _declspec(dllexport) int Decode(char* result,char* r);
int Decode(char* result,char* r)
{
//do sth.
return 0;
}
c#调用:
[DllImport("TestLib3.dll", CharSet = CharSet.Auto)]
public static extern int Decode(IntPtr result, IntPtr r);
。。。
int i = Decode(Marshal.StringToHGlobalAnsi("aaaaa"), Marshal.StringToHGlobalAnsi("7a"));
这只是其中一个尝试。我共做了以下几种尝试:
1. 直接传string,
声明:
[DllImport("TestLib3.dll", CharSet = CharSet.Auto)]
public static extern int Decode([MarshalAs(UnmanagedType.LPStr)]string result,[MarshalAs(UnmanagedType.LPStr)]string IntPtr r);
2. CharSet=CharSet.Ansi
3. 把返回值弄成char*,参数为空,然后声明:
[DllImport("TestLib3.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string Decode();//结果就这个能行
在debug的时候就是报错,可是直接双击程序运行又不报错。错误内容就是:
A call to PInvoke function 'CallTestLib3!CallTestLib3.Program::Decode' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
还有什么辄啊?google出来的方法我都试过了。或者怎么把这个错误忽略呢?
------解决方案--------------------
char* 用string或stringbuilder试试,另外调用约定指明 DllImport("",CallingConvention.Cdecl)
c++默认是cdecl