Write a C wrapper around C ++ classes with C ++ callbacks

I need to wrap a C ++ library with C. This C ++ library defines callback functions. For example:

// from C++ library typedef X CallbackFn(Y y); // X and Y are classes class Z { public: void addCallback( CallbackFn* fn ) { callbackFn = fn; } private: CallbackFn* callbackFn; }; 

In the C shell, I can define new C callbacks that cause C ++ callbacks. Something like that:

  // in C wrapper extern "C" { typedef int CallbackFnC(int n, ... ); CallbackFnC *callbackFnC; int addCallback(void* handle, CallbackFnC* fn) // handle is pointer to Z instance { callbackFnC = fn; ((Z*)handle)->addCallback(callbackFnCPP); } } X callbackFnCPP(Y y) { int rtn = callbackFnC(yn, ...); return X(rtn); } 

where I assume that I can match the corresponding elements of Y with the arguments to the C callback function and that I can just build the return type X from the return of C.

Will this work? No way to define new C callbacks?

Should the new C callback be inside extern "C" , and the specified C ++ callback instance should be outside?

+7
source share
1 answer

Yes, replacing the C ++ callback with the C-callback and the C ++ wrapper function will work (with some caveats) and not if the C ++ callback insists on passing / returning classes or references (as opposed to primitive types supported also by C), the wrapper method is the only possible solution.

The main caveat about using a wrapper function is that the wrapper function needs some sort of way to find the correct C function to call. Using global is a simple solution, but now you are limited to one callback for the entire program (regardless of the number of Z objects that you have). More flexible solutions will depend on the C ++ callback design and will vary on simple ones (when registering, you can provide arbitrary user data that will be provided for the callback) is very difficult.

+2
source

All Articles