C++ 回调C#函数的问题

ylkhao_hao 2010-08-05 11:28:43
需要在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都不行。。是什么原因呢?
...全文
912 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ylkhao_hao 2010-08-05
  • 打赏
  • 举报
回复
哎呀,,改对了。。多谢。。。。。。
gomoku 2010-08-05
  • 打赏
  • 举报
回复
此string(std::string)不是彼string(System.String)。
建议:回调函数中用LPCWSTR。
ylkhao_hao 2010-08-05
  • 打赏
  • 举报
回复
自己顶一下

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧