Reputation: 40159
PLEASE before closing as dupe, read the question & see why it is different (hint: it's the C compiler)
I have Googled and found many, many, explanations of how a C function can call a C++ member function.
They all look similar to the accepted answer to this question, from a very high rep member.
It says
In a header file, put
extern "C" void* MyClass_create() {
return new MyClass;
}
extern "C" void MyClass_release(void* myclass) {
delete static_cast<MyClass*>(myclass);
}
extern "C" void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id) {
static_cast<MyClass*>(myclass)->sendCommandToSerialDevice(cmd,params,id);
}
and, in the C code, put
void* myclass = MyClass_create();
MyClass_sendCommandToSerialDevice(myclass,1,2,3);
MyClass_release(myclass);
That seems straightforward, but what I don't understand is that the header file is going to have to reference MyClass
(never mind that static_cast
), but I want to compile my C code with a C compiler (gcc), not a C++ compiler (g++).
It won't work. How can I call a C++ member function from C code - which is compiled with a C compiler?
Upvotes: 3
Views: 1178
Reputation: 9113
You should do the following in C++:
In a C-compatible header file, e.g. interface.h
, write:
#if defined(__cplusplus)
extern "C" {
#endif
void* MyClass_create();
void MyClass_release(void* myclass);
void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id);
#if defined(__cplusplus)
}
#endif
and in a source file, e.g. interface.cpp
, put
/*extern "C"*/ void* MyClass_create() {
return new MyClass;
}
/*extern "C"*/ void MyClass_release(void* myclass) {
delete static_cast<MyClass*>(myclass);
}
/*extern "C"*/ void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id) {
static_cast<MyClass*>(myclass)->sendCommandToSerialDevice(cmd,params,id);
}
Now, compile these either as part of the original C++ library, or a separate C++ library. You should be able to include the above .h
file in your pure C programs and link them against the library.
Upvotes: 5