如何调用从C C ++的方法? [英] How to call a C++ method from C?
问题描述
我有一个C ++类,我有一些C编译的文件了。
我要调用它在C ++中定义的函数,实际上C ++类,所以我该怎么办?
以下声明,以显示我说什么:有可能会有语法错误:
serial_comm.cpp
MyClass类{
无效sendCommandToSerialDevice(INT命令,INT参数,诠释DEVICEID){
//一些codeS注意写入到串行端口。
}
}
external.c
INT主(INT ARGC,字符** argv的){
//我怎么在这里写?
}
解决这个问题的常见方法是提供一个C包装API。编写一个C函数,接受一个指向 MyClass的
对象(如 MyClass的
无效C,则需要提供了一些绰号,最简单的一种是移动无效*
左右)和参数的其余部分。然后里面的C ++进行函数调用:
的externCvoid *的MyClass_create(){
返回新MyClass的;
}
为externC无效MyClass_release(无效* MyClass的){
删除的static_cast< MyClass的*>(MyClass的);
}
为externC无效MyClass_sendCommandToSerialDevice(无效* MyClass的,INT CMD,INT参数,可以INT ID){
的static_cast< MyClass的*>(MyClass的) - GT; sendCommandToSerialDevice(CMD,则params,ID);
}
那么C code使用C API来创建对象,调用函数与释放对象:
// C
void *的MyClass的= MyClass_create();
MyClass_sendCommandToSerialDevice(MyClass的,1,2,3);
MyClass_release(MyClass的);
I have a C++ class and I'm compiling it with some C files.
I want to call a function which is defined in C++, actually in C++ class, so what am I going to do?
The following declarations to show what am I saying: there may there be syntax errors:
serial_comm.cpp
class MyClass {
void sendCommandToSerialDevice(int Command, int Parameters, int DeviceId) {
//some codes that write to serial port.
}
}
external.c
int main(int argc, char ** argv) {
//what am I going to write here?
}
The common approach to this problem is providing a C wrapper API. Write a C function that takes a pointer to a MyClass
object (as MyClass
is not valid C, you will need to provide some moniker, simplest one is moving void*
around) and the rest of the arguments. Then inside C++ perform the function call:
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);
}
Then the C code uses the C api to create the object, call the function and release the object:
// C
void* myclass = MyClass_create();
MyClass_sendCommandToSerialDevice(myclass,1,2,3);
MyClass_release(myclass);
这篇关于如何调用从C C ++的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!