c#调用c++dll库调用约定问题

DEBUG 错误现象提醒 
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention 
release版本 应用程序直接消失,什么信息都没有。
 
c#和c++ 都是明确定义了 __stdcall为函数调用约定,但debug版本调试还是提示上述现象,大意就是回调函数的调用约定不一致。
经排查其实不是调用约定不一致,而是回调函数的参数不一致,造成回调函数释放栈内存是异常。
 
c++dll库中 回调函数定义 typedef void (CALLBACK *pRHMessageCallBack)(int iVK_Value, int iFlag, void* pUserData);
 
c#中应该这样定义才正确:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void pRHMessageCallBack(int iVK_Value, int iFlag, IntPtr userData);

而不能定义成 

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void pRHMessageCallBack(int iVK_Value, int iFlag, object userData);

原文地址:https://www.cnblogs.com/chncongblog/p/3966933.html