C++ 回调C#函数的问题
需要在C++回调C#函数
核心代码如下(只是测试,发现不行)
C++部分:
typedef void (*ShowMsgCallBack)(string sMsg);
extern "C" _declspec(dllexport) bool RegCallBack(ShowMsgCallBack fHandlerFunc);
extern "C" _declspec(dllexport) bool Start();
ShowMsgCallBack g_ShowMsgCallBack = NULL;
bool RegCallBack(ShowMsgCallBack fHandlerFunc)
{
g_ShowMsgCallBack = fHandlerFunc;
return true;
}
bool Start()
{
string sMsg("just for test");
if (g_ShowMsgCallBack != NULL)
{
g_ShowMsgCallBack(sMsg);
}
return true;
}
C#部分
public delegate void ShowMessage(string sMsg);
[DllImport("TestDll.dll",SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern bool RegCallBack(ShowMessage fHandlerFunc);
[DllImport("TestDll.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern bool Start();
public void ShowMsg(string sMsg)
{
MessageBox.Show(sMsg, this.Text, MessageBoxButtons.OK);
}
private void button3_Click(object sender, EventArgs e)
{
ShowMessage tmpShowMsg = new ShowMessage(this.ShowMsg);
RegCallBack(tmpShowMsg);
}
private void button4_Click(object sender, EventArgs e)
{
Start();
}
程序运行的时候,MessageBox弹出来了,但是“just for test”没有显示,然后程序就崩掉了。
提示调用约定不一致。我试了把C++工程的调用约定改为了_stdcall和__cdecl都不行。。是什么原因呢?