上一章根据实施例讲解了C++回调函数的应用“https://blog.csdn.net/ETNthrough/article/details/131638784?spm=1001.2014.3001.5502”
本文将讲解如何通过C#调用C++的回调函数,具体原理可查看
①https://www.jianshu.com/p/2f695d6fd64f
②https://zhuanlan.zhihu.com/p/326902537
C# C++也可以参考“https://blog.csdn.net/Vaccae/article/details/111596267”
说明:C#调用C++,本文将以DLL方式举例
一、C++模块
jni.h
/*
extern "C"、__declspec(dllexport)是声明接口的规则
*/
//回调功能 更新curIdx值
typedef void(__stdcall * progressCallback)(int* curIdx);
//接口
extern "C" int __declspec(dllexport) func(int a_in,int b_in,
progressCallback progressCB);
jni.cpp
int func(int a_in,int b_in,progressCallback progressCB)
{
//加法运算
int sum=a_in+b_in;
progressCB(&sum);
//减法运算
int diff=a_in-b_in;
progressCB(&diff);
//乘法运算
int mul=a_in*b_in;
progressCB(&mul);
return 0;
}
二、C#端
①C#接口声明
namespace cSharp
{
class DLLApi
{
//对应于C++回调函数
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void ProgressCallback(ref intvalue);
[DllImport("xxx.dll", EntryPoint = "func", CallingConvention = CallingConvention.Cdecl)]
public static extern int func(int a_in,int b_in,ProgressCallback progressCB);
/*
C#中接口的声明规则这里不作叙述,“xxx.dll是C++中接口及算法生成的DLL供C#调用”
EntryPoint 中对应于接口中各个功能函数名
*/
}
}
②C#接口调用(这里以按钮触发为例)
private void button_Click(object sender, EventArgs e)
{
int a=4;
int b=2;
int idx=new int();
//用于实时显示回调函数更新的值
DLLApi.ProgressCallback callback =
(ref int schedule) =>
{
idx = schedule;
this.label.Text = idx.ToString();
//这一句是当回调触发时自动更新
Application.DoEvents();
};
int res = DLLApi.func(a,b, callback);
}
触发按钮,label值将依次更新:6、2、8

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



