In many occasions, C frameworks use function pointers to extend functionality and notify listeners (for example win32-api and GLUT). When programming object-oriented C++ you prefer to use classes and objects to handle this. So my question is:
Is it safe to use a pointer to a static method where a C library is expecting a function pointer?
Formally, no, you can't do it, but in practice, yes. To be callable from C code, a C++ function must be marked extern "C"
, to ensure that it uses the calling convention that the C compiler expects. There is no way to mark a static member function as extern "C"
, so no way to guarantee that it can be called successfully from C code. I don't know of a compiler that doesn't use the same calling convention for static member functions as for C code, so this will work. Some compilers will produce a warning for this situation, because, technically, the function has the wrong type. In fact, if you look at the C++ standard, C functions that take callbacks (qsort
, for example) have two versions: one that takes an extern "C"
function and one that takes an extern "C++"
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With