c#写程序有时需要调用c++编译的dll,普通的调用方法比较简单。有时调用回调函数就有些迷茫了。通过c#的委托可以实现c++的回调,简单介绍下:
1、首先添加using System.Runtime.InteropServices;
引用c++的dll
创建个委托:
public delegate void IndexFunc(int n, int index);
[DllImport(@"D:/SDK.dll")]
private static extern bool InfoCallBack(int n, IndexFunc Func, int index);
public bool IndexInfoCallBack(int n, IndexFunc Func, int index)
{
return InfoCallBack(n, Func, index);
}
2、窗体调用
private void button1_Click(object sender, EventArgs e)
{
IndexFunc func=new IndexFunc(ssss);
bool a = IndexInfoCallBack(0, cbfunc, 0);
}
当执行IndexInfoCallBack的时候就实现callback并将回调回来的函数付给ssss方法中的m,n
public void ssss(int m, int n)
{
MessageBox.Show(m.ToString()+n.ToString());
}
本文介绍了如何在C#程序中调用C++编译的DLL,并使用委托实现C++的回调功能。通过添加using System.Runtime.InteropServices;引用C++ DLL,定义委托类型,设置DllImport以及在窗体事件中触发回调,详细步骤包括创建委托、声明外部方法、在按钮点击事件中调用并传入回调方法。
697

被折叠的 条评论
为什么被折叠?



