在c#里调用C++的dll,遇到了一些头疼的问题:
C++里头文件定义形势如下:
typedef void (*CALLBACKFUN1W)(wchar_t*, void* pArg);
typedef void (*CALLBACKFUN1A)(char*, void* pArg);
bool BIOPRINT_SENSOR_API dllFun1(CALLBACKFUN1 pCallbackFun1, void* pArg);
在其中一个导入的dll方法里,有一个回调函数的参数
[DllImport("test.dll", EntryPoint = "dllFunc1", CharSet = CharSet.Unicode)]
public static extern bool dllFunc1([MarshalAs(UnmanagedType.FunctionPtr)] CallbackFunc1 pCallbackFunc1 , IntPtr pArg);
回调函数在C#里定义成委托如下:
public delegate void CallbackFunc1(StringBuilder strName, IntPtr pArg);
调试运行,报错。
有时是直接出错退出,信息如下:
Buffer overrun detected!
Program:
...
A buffer overrun has been detected which has corrupted the program's internal state. The program cannot safely continue execution and must now be terminated.
有时则能运行起来,但会抛出异常:
System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
几经周折,觅得答案,原来是要指定 调用方式,如下就OK了:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void CallbackFunc1(IntPtr hWnd, IntPtr pArg);
而系统默认方式为 CallingConvention.StdCall。
程序终于不报错了,但是又出现结果不对了