c++ - 具有 C++ 数据结构的 C 代码

标签 c++ c gcc

我知道这不是开发项目的好方法,但由于我工作的某些原因,我致力于在 C 项目中集成 C++ 中的一些数据结构(LRU 缓存和 HashMap )。

到目前为止,我知道有一些方法可以使用 extern "C" 在 C++ 中调用 C 函数,但是从 C 调用 C++ 对象(方法...)呢?

我正在使用 GCC。

最佳答案

如果所有代码都是用 C++ 编译器编译的,应该没有(或很少)问题。

如果您使用 gcc 编译 C 并使用 g++ 编译 C++,那么您需要围绕您的类编写 header 包装器,以通过一组函数使 C++ 代码可见。

例子:

我的类.h

#ifdef __cplusplus


class MyClass
{
    public:
       MyClass() {/*STUFF*/}
       ~MyClass() {/*STUFF*/}

       int doStuff(int x, float y) {/*STUFF*/}
};

extern "C" {
#endif

/* C Interface to MyClass */

void*   createMyClass();
void    destroyMyClass(void* mc);
int     doStuffMyClass(void* mc, int x, float y);

#ifdef __cplusplus
}
#endif

源文件

我的类.cpp

#include "MyClass.h"

void*   createMyClass()           {return reinterpret_cast<void*>(new MyClass);}
void    destroyMyClass(void* mc)  {delete reinterpret_cast<MyClass*>(mc);}

int     doStuffMyClass(void* mc, int x, float y)
{
    return reinterpret_cast<MyClass*>(mc)->doStuff(x,y);
}

您的 C 代码现在只包含“MyClass.h”并使用提供的 C 函数。

MyCFile.c

#include "MyClass.h"

int main()
{
    void* myClass =  createMyClass();
    int value = doStuffMyClass(myClass, 5, 6.0);
    destroyMyClass(myClass);
}

关于c++ - 具有 C++ 数据结构的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16777938/

相关文章:

c - 加载 DLL 库

java - 如何在Java编写的IDE中集成GCC编译器?

c++ - C++ 中 "enumeration type"和 "enumerated type"有什么区别?

c++ - 用Lambda函数重新捕获变量是否合法?

c++ - 使用空终止字符数组调试断言失败错误

c - C 中的多个信号会导致段错误吗?

c++ - Clang 3.1 + libc++ 编译错误

c++ - 模板函数中的 "C4430: missing type specifier - int assumed"

c - strncat 添加了一些意外的字符

c - C 新手,简单代码不起作用