It just looks like what I'm working on right now.
Here's a blog post about providing your own callbacks using C ++ classes: http://blogs.microsoft.co.il/blogs/alon/archive/2007/05/29/Native-Callback.aspx
I am not familiar with calls to C ++ member functions from C, but I made an interface class (abstract base) for another C ++ class for callbacks (similar to the article). Here is a basic example of what I provide for the bridge:
Now, in order to make this available for managed provider implementations, we need to create a series of classes that provide a bridge.
// Where gcroot is defined
Edit: Added code to display without using the managed interface class class that I am using.
Here is a modified version of my example that can be used to fit your CLibFunc above. This assumes that the C function is making a callback.
It can also be slightly reduced depending on how your callback classes are involved and how much freedom you need to expand.
// Where gcroot is defined #include <vcclr.h> // C callback signature // Second parameter is meant to point to the calling C++ object typedef int (__stdcall CLIBCALLBACK) (int param1, void *caller); // C library function void CLibFunc(CLIBCALLBACK *callback, void *caller) { // Do some work (*callback)(1234, caller); // Do more work } // Managed caller interface class public interface class IManagedCaller { void EventFunction(int param1); }; // C++ native bridge struct struct CCallerBridge { // Give the managed class full access friend ref class ManagedCaller; // Store a reference to the managed object for callback redirects gcroot<IManagedCaller ^> m_rManaged; public: // Cast the caller to the native bridge and call managed event function // Note: This must be __stdcall to prevent function call stack corruption static int __stdcall CallBackImpl(int param1, void * caller) { CCallerBridge * pCaller = (CCallerBridge *) caller; pCaller->m_rManaged->EventFunction(param1); return 0; } }; // C++/CLI caller class public ref class ManagedCaller : public IManagedCaller { // Pointer to the native bridge object CCallerBridge * m_pNative; public: ManagedCaller() { // Create the native bridge object and set the managed reference m_pNative = new CCallerBridge(); m_pNative->m_rManaged = this; } ~ManagedCaller() { delete m_pNative; } // Calls the C library function void CallerFunction() { CLibFunc(CCallerBridge::CallBackImpl, m_pNative); } // Managed callback function virtual void EventFunction(int param1) { Console::WriteLine(param1); } }; // Usage int main(array<System::String ^> ^args) { ManagedCaller ^ oCaller = gcnew ManagedCaller(); oCaller->CallerFunction(); return 0; }
Cuppm
source share