.net - How to handle C++ Native Callback Class in managed wrapper -
.net - How to handle C++ Native Callback Class in managed wrapper -
i've seen possible duplicate semantics different havent' been able working until now. i'm not sure comparable pure c-function pointer style, i've used in different projects.
i have dll defines native c++ callback this:
class="lang-or-tag-here prettyprint-override">class nativeclass { // native callback handler class, internal definition class callback { public: // constructor callback() {} // destructor virtual ~callback() {} // callback functions virtual void handler() {} }; setcallback(callback* p) { ... } ...
the dll consumes , fires callback function:
setcallback(nativeclass::callback* p);
so when i'm writing c++/cli wrapper, how can pass reference managed object exposing such callback handler.
is not possible or how have handle correctly ? i've tried next according msdn documentation , other answers:
typedef (__stdcall *native_callback)(void); public delegate void managedcallback(); ... public ref class wrapper { public: callback* _cbhandlernative; nativeclass* nc; wrapper() { _cbhandlernative = new nativeclass::callback(); _nc = new nativeclass(); // seek assigning function pointer, fails intptr ip = marshal::getfunctionpointerfordelegate(gcnew managedcallback(this, &wrapper::tobecalled)); _cbhandlernative->handler = static_cast<native_callback>(ip.topointer()); _nc->setcallback(_cbhandlernative); } // managed handler void tobecalled() { ... }
i have solution, seems working correctly:
first, i'm defining native proxy class holding callbacks:
public class cbproxy : callback { public: native_callback _cbhandler; virtual void handler() { if(_cbhandler != null) _cbhandler(); } }
now can attach managed delegate handler proxy , pass native dll.
public delegate void managedcallback (); managedcallback^ mcb = gcnew managedcallback (this, &wrapper::tobecalled); intptr ip = marshal::getfunctionpointerfordelegate(mcb); _pcbproxy->_cbhandler = static_cast<native_callback>(ip.topointer()); // ensure maintain reference callback, otherwise // freed gc::keepalive(mcb); gc::keepalive(ip); _nc->setcallback(_pcbproxy);
i'm not sure whether there more efficient way, works @ first sight me right now.
.net delegates c++-cli interop function-pointers
Comments
Post a Comment