Reputation: 4254
I want to call a C API from C++. The API expects a function pointer, though for me the functionality is implemented in a C++ function object because it has state.
In fact the desired functionaliity is split across into two function objects. The C api expects a function that has two pointer parameters for returning the two things that each of the function objects return.
Apart from defining a global function is there any way of using the function object from C. For example can it be reinterpret_casted to a function pointer ?
EDITS:
For simplicity its ok to assume that the signature of the call back is void (*f)(void*, int*, int*)
Oh and it has to be C++-03
Upvotes: 0
Views: 263
Reputation: 30011
Most APIs allow you to pass some kind of user state along through a void pointer. You can pass a pointer to your object through there:
struct my_obj
{
void operator()(int*, int*) {}
static void forwarder(void *state, int *x, int *y) { (*(my_obj*)state)(x, y); }
};
void install_fn(void (*)(void*,int*,int*), void *state);
my_obj obj;
install_fn(my_obj::forwarder, &obj);
For APIs which don't allow you to pass any state (GLUT is one of the only ones I've found that come to mind), you're out of (portable) luck.
Upvotes: 3