C 函数调用 C++ 成员函数 - C 代码是用 C 编译器编译的

C function calling C++ member function - where the C code is compiled with a C compiler

在关闭之前阅读问题并了解它为什么不同(提示:它是 C 编译器)

我用 Google 搜索并找到了很多关于 C 函数如何调用 C++ 成员函数的解释。

它们看起来都与来自非常高代表成员的 this question 的公认答案相似。

它说

在头文件中,放入

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使用 C 编译器 (gcc) 而不是 C++ 编译器 (g++) 编写代码。

不行。如何从使用 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,放

/*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++ 库进行编译。您应该能够将上述 .h 文件包含在您的纯 C 程序中,并 link 它们针对库。