c++ Cx将委托传递给原生c++

C++ Cx passing delegates to native c++

本文关键字:c++ 原生 Cx      更新时间:2023-10-16

我需要找到一种方法来检索回调从c++/Cx回本机c++。在c++代码中,这些指针存储为函数指针,而在c++/Cx中,它们存储在委托中。我发现在c#和c++/CLI中有一个类似GetFunctionPointerForDelegate()的函数,但似乎在c++/CX中没有类似的函数。这个问题真的有解决办法吗?

c++/Cx是c#应用程序和c++原生库之间的中间层。我设法将指针从c#传递到WinRt(c++/Cx)层,如下所示:

del d = new del(callBackFunction);                  //declare a delegate and               
                                                    //add a function to delegate
IntPtr p = GetFunctionPointerForDelegate(d);        //retrieve pointer
w.retrieveCallbackFunction(p.toInt32());    //pass a pointer as int to WinRt layer

在WinRt层内部的retrieveCallbackFunction:

void* x=(void*)p;            //cast it to void*
callbackFunctionType ptr = (callbackFunctionType)x;   // cast it to a type
                                                      // of function pointer
ptr(...);            //call function

我知道这不是最好的解决方案,但是这个方法现在对我很有效。

编辑

防止垃圾收集器收集函数或委托也是一个好主意

GCHandle callbackHandle = GCHandle.Alloc(d); // !!!!

我对c++/CX没有任何线索,但快速搜索后发现这对我来说听起来像是你想要完成的:

codeproject.com:将委托转换为函数指针以实现回调函数