Reputation:
I am using a driver written in pure C. It has some callbacks registered to it. When those are called they will interact with C++ code.
I tried to access functions in a namespace in the callback but that have me an error which made me think they can't call C++ code which makes a lot of sense I guess. But then I realized I was interacting with C++ classes with no problem.
So is it allowed for a callback executed in C code to call C++ specific functioanlity like namespaces and classes?
Upvotes: 0
Views: 102
Reputation: 27365
So is it allowed for a callback executed in C code to call C++ specific functioanlity like namespaces and classes?
Yes. The usual solution to this is to create an opaque (void*) object that holds the pointer of your class, and a set of callbacks declared as extern "C"
in your C++ code, that receive the void *
, reinterpret_cast
it to your class pointer and call the appropriate functions.
If you do not need classes remembered for your callbacks, you can dispense of the void*
and the reinterpret_cast
stuff but the callbacks in C++ still need to be declared as extern "C"
for the C code to be able to call them.
Upvotes: 0
Reputation: 27567
You need to #include
the header as a C file:
extern "C" {
#include "c_file.h"
}
Upvotes: 2