Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Method as Function Pointer

Tags:

c++

c

oop

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?

like image 302
Jens Åkerblom Avatar asked Dec 21 '22 07:12

Jens Åkerblom


1 Answers

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.

like image 198
Pete Becker Avatar answered Dec 24 '22 02:12

Pete Becker