3

I have a c library function with the prototype:

int setCallback(void* callback_function);

It can accept a c function that matches

int myCallback(int x);
setCallBack(myCallback);  // register function as callback

Now, I want to use this c library in a c++ project, and have it call a c++ function defined in a namespace. Passing the equivalent c++ function however, gives the error with g++ 5.4.0:

setCallBack(myCPPCallBack);  // ERROR!
invalid conversion from ‘int (*)(int)’ to ‘void*’ [-fpermissive]

I can get it to build and run this by doing the following cast.

setCallBack((void*)myCPPCallBack);

My question is, is this undefined behavior or otherwise unwise to do so? What are the risks, and is there an alternative?

AT_BN
  • 31
  • 1
  • How certain are you that the `callback_function` is really supposed to be an `int (*)(int)`? – Mooing Duck Mar 05 '19 at 23:40
  • Hi AT_BN! I think this Q/A might answer your question: [Function pointers casting in C++](https://stackoverflow.com/questions/1096341/function-pointers-casting-in-c) – Haldean Brown Mar 05 '19 at 23:41
  • You should also read about [stdcall and cdecl](https://stackoverflow.com/q/3404372/1553090) – paddy Mar 05 '19 at 23:43

0 Answers0