Static method as a function pointer

In many cases, C frames 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 possible to use a pointer to a static method in which the C library expects a function pointer?

+4
source share
1 answer

Formally, no, you cannot do this, but in practice, yes. To be called from C code, the C ++ function must be labeled extern "C" to ensure that it uses the calling convention that C compiler expects. It is not possible to mark a static member function as extern "C" , therefore it cannot be guaranteed that it can be successfully called from C code. I do not know a compiler that does not use the same calling convention for static member functions as for C code, so this will work. Some compilers give a warning for this situation, because technically the function is of the wrong type. In fact, if you look at the C ++ standard, C functions that accept callbacks (like qsort , for example) have two versions: one that accepts an extern "C" function and a function that accepts an extern "C++" function.

+11
source

All Articles