4

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?

1
  • I believe so, in pre C++11 I use static functions as the thread procedure when creating new threads. I'm sure there could be issues with calling conventions (stdcall, fastcall etc). I'm sure somebody else not on their iPhone will provide a nice in depth answer! (Also regarding "reference", You should use a function pointer if the library expects a function pointer). Commented Mar 29, 2013 at 12:39

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.