调用C ++成员函数的C函数-使用C编译器编译C代码 [英] C function calling C++ member function - where the C code is compiled with a C compiler
问题描述
请 ,在以欺骗手段关闭之前,请先阅读问题&看看它为何与众不同(提示:它是C编译器)
PLEASE before closing as dupe, read the question & see why it is different (hint: it's the C compiler)
我已经用Google搜索了,发现了很多关于C函数如何调用C ++成员函数的解释。
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.
它说
在头文件中,放入
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);
}
,然后在C代码中放入
void* myclass = MyClass_create();
MyClass_sendCommandToSerialDevice(myclass,1,2,3);
MyClass_release(myclass);
这似乎很简单,但是我不明白的是,头文件必须参考 MyClass
(不要介意 static_cast
),但是我想用C编译器(gcc)编译C代码,而不是C ++编译器(g ++)。
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++).
它不起作用。如何从用C编译器编译的C代码中调用C ++成员函数?
It won't work. How can I call a C++ member function from C code - which is compiled with a C compiler?
推荐答案
您应该执行以下操作在C ++中:
You should do the following in C++:
在与C兼容的头文件中,例如 interface.h
,写:
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
并在源文件中,例如 interface.cpp
,放
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);
}
现在,将它们作为原始C ++库的一部分或单独编译C ++库。您应该能够在纯C程序中包含上述 .h
文件,并将其链接到库。
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.
这篇关于调用C ++成员函数的C函数-使用C编译器编译C代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!