简体   繁体   English

C代码与C ++数据结构

[英]C code with C++ data structures

I know that this is not a good way of developing of a project, but for some reasons of my work I am committed to integrate some data structures in C++ (LRU cache and hash map) in a C project. 我知道这不是开发项目的好方法,但由于我工作的一些原因,我致力于在C项目中集成C ++(LRU缓存和哈希映射)中的一些数据结构。

So far I know that there is some way to call C functions in C++ using extern "C" , but what about calling C++ objects (methods...) from C? 到目前为止,我知道有一些方法可以使用extern "C"在C ++中调用C函数,但是从C调用C ++对象(方法......)呢?

I am using GCC. 我正在使用GCC。

Write a C wrapper around your C++ interface. 在C ++接口周围编写一个C包装器。 Compile it as C++, but make sure to include your C interface in an extern "C" block. 将其编译为C ++,但请确保将C接口包含在extern "C"块中。 This new interface should link fine with your C program and provide you with access to your C++ code. 这个新界面应与您的C程序良好链接,并为您提供对C ++代码的访问。

If all the code is being compiled with C++ compiler there should be no (or very little) problem. 如果使用C ++编译器编译所有代码,则应该没有(或很少)问题。

If you have C compiled with gcc and C++ compiled with g++ then you need to write a header wrapper around your class to make the C++ code visable via a set of functions. 如果您使用gcc编译的C和使用g ++编译的C ++,那么您需要在类周围编写一个包装器,以通过一组函数使C ++代码可见。

Example: 例:

MyClass.h MyClass.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

Source File 源文件

MyClass.cpp MyClass.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);
}

Your C code now just include "MyClass.h" and uses the C functions provided. 您的C代码现在只包含“MyClass.h”并使用提供的C函数。

MyCFile.c MyCFile.c

#include "MyClass.h"

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

You need to create C compatible forwarding functions that take as their first parameter a pointer to the object. 您需要创建C兼容的转发函数,将第一个参数作为指向对象的指针。 The forwarding function will then [typically] cast the first parameter to the correct object type and call the appropriate member function. 然后,转发功能[通常]将第一个参数转换为正确的对象类型并调用适当的成员函数。

// Function declaration in header
extern "C" void function(void *object, int param1, int param2);

// Function definition in source file
extern "C" function(void *object, int param1, int param2)
{
     static_cast<Object*>(object)->member_function(param1, param2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM