I've seen the possible duplicate but the semantics are slightly different so I havent' been able to get it working until now. I'm not even sure it is really comparable to the pure c-function pointer style, which I've already used in different projects.
I have a DLL which defines a native C++ callback like this:
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 then consumes and fires the Callback by this function:
SetCallBack(NativeClass::Callback* p); So when I'm writing my C++/CLI wrapper, how can I pass a reference to a managed object exposing such a callback handler.
Is something like this generally not possible or how would I have to handle that correctly ? I've tried the following now according to the MSDN documentation and other SO 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(); // try assigning function pointer, but 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() { ... }