从C#回调到C ++ [英] Callback from C# to C++
问题描述
我开发了一个小型C ++应用程序,它使用本文中的指导方针调用托管的.NET C#COM对象:
从非托管C ++代码调用托管.NET C#COM对象 [ ^ ]
现在我想在我的.NET应用程序中调用的C ++应用程序中建立一个回调函数。我想在.NET端创建一个函数 - 从C ++应用程序调用的RegisterCppCallback。并将某种函数指针作为参数。
我的想法是在.NET端应该看起来像这样:
public delegate void CppCallbackFn();
CppCallbackFn myCallbackFunc;
public void RegisterCppCallback( IntPtr pfn)
{
myCallbackFunc =(CppCallbackFn)(Marshal.GetDelegateForFunctionPointer(pfn, typeof (CppCallbackFn))) as CppCallbackFn;
myCallbackFunc(); // 测试
}
和CPP方面:
typedef int(__ stdcall * CallbackFunc)();
CallbackFunc * mInstance;
int CallbackHandler()
{
// some代码
返回 0 ;
}
// 在.NET中调用RegisterCppCallback函数
mInstance = new CallbackFunc((CallbackFunc)CallbackHandler);
pDotNetCOMPtr-> RegisterCppCallback(( long )mInstance);
我的问题是没有调用CPP中的回调函数。
我做错了什么?任何帮助都非常感谢
这可能如何从C / C ++代码回调C# [ ^ ]文章帮助你?
编辑(0):
这涵盖了相反的情况: pinvoke-c-callback-from-c [ ^ ]。
编辑(1):
为了从C ++端建立回调(在托管类中注册它们),我总是使用混合模式C ++程序集。这样我就可以访问这两个世界(来自未管理的C ++代码的托管类实例,反之亦然)。
p.d.忘掉这个解决方案并将其投入使用。
我找到了解决问题的方法。只需将上面列出的代码中的最后一行更改为:
pQGISInterfacePtr-> RegisterCppCallback((long)CallbackHandler);
I've developed a small C++ application that calls a managed .NET C# COM object using the guide lines in this article:
Calling Managed .NET C# COM Objects from Unmanaged C++ Code[^]
Now I would like to establish a callback function in my C++ application that is called from my .NET application. I want to create a function on the .NET side - RegisterCppCallback that is called from the C++ app. and takes some kind of function pointer as argument.
My idea is that is should look something like this on the .NET side:
public delegate void CppCallbackFn();
CppCallbackFn myCallbackFunc;
public void RegisterCppCallback(IntPtr pfn)
{
myCallbackFunc = (CppCallbackFn) (Marshal.GetDelegateForFunctionPointer(pfn, typeof(CppCallbackFn))) as CppCallbackFn;
myCallbackFunc(); // test it
}
and on the CPP side:
typedef int (__stdcall* CallbackFunc)();
CallbackFunc * mInstance;
int CallbackHandler()
{
// some code
return 0;
}
// call the RegisterCppCallback function in .NET
mInstance = new CallbackFunc((CallbackFunc) CallbackHandler);
pDotNetCOMPtr->RegisterCppCallback((long) mInstance);
My problem is that the callback function in CPP isn't called.
What am I doing wrong ? Any help is highly appreciated
Might this How to make a callback to C# from C/C++ code[^] article help you?
EDIT(0):
This covers the oposite case: pinvoke-c-callback-from-c[^].
EDIT(1):
For establishing callbacks from the C++ side (registering them in a managed class) I've always used mixed mode C++ assemblies. That way I was able to have access to both worlds (managed class instances from unamanged C++ code and viceversa).
p.d. forget about this solution and downvote it.
I've found the solution for my problem. Just change the last line in the above listed code to:
pQGISInterfacePtr->RegisterCppCallback((long) CallbackHandler);
这篇关于从C#回调到C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!