C函数调用C ++成员函数 – 其中C代码是用C编译器编译的
请关闭之前,阅读问题,看看为什么它不同(提示:它是C编译器)
我已经谷歌搜索了很多很多关于C函数如何调用C ++成员函数的解释。
它们看起来都类似于这个问题的接受答案,来自一个非常高的rep成员。
它说
在头文件中,放
extern "C" void* MyClass_create() { return new MyClass; } extern "C" void MyClass_release(void* myclass) { delete static_cast(myclass); } extern "C" void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id) { static_cast(myclass)->sendCommandToSerialDevice(cmd,params,id); }
并且,在C代码中,放
void* myclass = MyClass_create(); MyClass_sendCommandToSerialDevice(myclass,1,2,3); MyClass_release(myclass);
这看起来很简单,但我不明白的是头文件必须引用MyClass
(不要介意static_cast
),但我想用C编译器(gcc)编译我的C代码,而不是C ++编译器(克++)。
它不会起作用。 如何从C代码调用C ++成员函数 – 这是用C编译器编译的?
您应该在C ++中执行以下操作:
在C兼容的头文件中,例如interface.h
,写:
#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
并在源文件中,例如interface.cpp
,put
/*extern "C"*/ void* MyClass_create() { return new MyClass; } /*extern "C"*/ void MyClass_release(void* myclass) { delete static_cast(myclass); } /*extern "C"*/ void MyClass_sendCommandToSerialDevice(void* myclass, int cmd, int params, int id) { static_cast(myclass)->sendCommandToSerialDevice(cmd,params,id); }
现在,将它们作为原始C ++库的一部分或单独的C ++库进行编译。 您应该能够在纯C程序中包含上述.h
文件,并将它们链接到库中。