C++回调到C#的回调假设我有一个计算PI的C++库函数://pi.h:#ifdefBUILDING_DLL#defineDLL_MACRO__declspec(dllexport)#else#defineDLL_MACRO__declspec(dllimport)#endifnamespaceCpp{classPI{public:staticdoubleDLL_MACROcompute();};};//pi.cpp:#include"pi.h"#includedoubleCpp::PI::compute(){//莱布尼茨求和公式:doublesum=0.0;for(longn=0;n<100*1000*1000;n++)sum+=4.0*pow(-1.0,n)/(2*n+1.0);返回总和;我需要从C#调用这个函数,我想使用C++/CLI作为“桥梁”。但是这个C++函数有点慢。因此,调用此函数的C#代码需要获得一个回调函数,告诉它该函数的进度是多少。C#代码可能需要一些状态(例如进度条)来处理此信息。因此,来自C++的回调必须进入C#端的成员函数。所以我介绍://piCLI.h:C#和C++之间的C++/CLI“桥梁”#include"pi.h"#pragmaoncenamespaceCLI{publicrefclassPIabstract{public:doublecompute(){returnCpp::PI::计算();}virtualvoidprogress(intpercentCompleted)=0;};};和命名空间CSharp{publicclassPI:CLI.PI{publicoverridevoidprogress(intpercentCompleted){System.Console.WriteLine(percentCompleted+"%completed.");}}}调用CSharp.PI.compute()现在工作正常:-)。它按预期将调用转发给Cpp::PI::compute()。但是,如何让C++库在Cpp::PI::compute()运行时将进度更新转发到CSharp.PI.progress()呢?提前感谢任何答案!我也会采用函数指针/委托方法://pi.h:#pragmaonce#ifndefDLL_MACRO#ifdefBUILDING_DLL#defineDLL_MACRO__declspec(dllexport)#else#defineDLL_MACRO__declspec(dllimport)#endif#endifnamespaceCpp{typedefvoid(__stdcall*ComputeProgressCallback)(int);类PI{public:staticdoubleDLL_MACROcompute(ComputeProgressCallbackcallback);};}//pi.cpp:#include"pi.h"#includedoubleCpp::PI::compute(Cpp::ComputeProgressCallbackcallback){doublesum=0.;for(longn=0L;n!=100000000L;++n){sum+=4.*std::pow(-1.,n)/(2L*n+1.);回调(/*实现*/);}返回总和;}//piCLI.h:C#和C++之间的C++/CLI“桥梁”#pragmaonce#include"pi.h"namespaceCLI{publicdelegatevoidComputeProgressDelegate(intpercentCompleted);publicrefclassPIabstractsealed{public:staticdoublecompute(ComputeProgressDelegate^callback){使用System::IntPtr;使用System::Runtime::InteropServices::Marshal;IntPtrcbPtr=Marshal::GetFunctionPointerForDelegate(回调);返回Cpp::PI::compute(static_cast(cbPtr.ToPointer()));}};}namespaceCSharp{publicstaticclassPI{publicstaticdoublecompute(){CLI.PI.compute(percentCompleted=>System.Console.WriteLine(percentCompleted.ToString()+"%completed."));}}}或者,要覆盖抽象方法而不是在C#端创建委托://piCLI.h:TheC++/CLI"bridge"betweenC#andC++#pragmaonce#include"pi.h"namespaceCLI{public参考类PI抽象{委托voidComputeProgressDelegate(intpercentCompleted);public:doublecompute(){使用System::IntPtr;使用System::Runtime::InteropServices::Marshal;ComputeProgressDelegate^callback=gcnewComputeProgressDelegate(this,&PI::progress);IntPtrcbPtr=Marshal::GetFunctionPointerForDelegate(回调);返回Cpp::PI::compute(static_cast(cbPtr.ToPointer()));}protected:virtualvoidprogress(intpercentCompleted)摘要;};}namespaceCSharp{publicsealedclassPI:CLI.PI{protectedoverridevoidprogress(intpercentCompleted){System.Console.WriteLine(percentCompleted.ToString()+"%completed.");}}}将C++/cli定义的Native函数作为回调传递给您的本机C++,并使用gcroot在回调上调用您的托管C#函数。以上就是C#学习教程:从C++回调到C#回调分享的全部内容,如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
