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 wrapper I could define new C callbacks, which call the C++ callbacks. Something like this:
// 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(y.n, ...);
return X(rtn);
}
where I assume I can map the relevant members of Y to the arguments of the C callback function and that I can sufficiently construct the return type X from the C return.
Is this going to work? There's no way around defining the new C callbacks?
The new C callback should be inside the extern "C"
and the defined instance of the C++ callback should be outside?
extern "C"
function pointers are compatible with C++ linkage function pointers is implementation-defined. For portability, you need to use the approach you show. – Pointsman