Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C code with C++ data structures

Tags:

c++

c

gcc

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.

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?

I am using GCC.

like image 674
Vicente Bolea Avatar asked May 27 '13 17:05

Vicente Bolea


People also ask

Can we use data structures in C?

The C Programming language has many data structures like an array, stack, queue, linked list, tree, etc. A programmer selects an appropriate data structure and uses it according to their convenience.

Can I learn DSA in C language?

In this Data Structures and Algorithms Through C In Depth course, C language programs are used for implementing various concepts, but you can easily code them in any other programming languages like C++, C#, Java, Python.


1 Answers

If all the code is being compiled with C++ compiler there should be no (or very little) problem.

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.

Example:

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

#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.

MyCFile.c

#include "MyClass.h"

int main()
{
    void* myClass =  createMyClass();
    int value = doStuffMyClass(myClass, 5, 6.0);
    destroyMyClass(myClass);
}
like image 138
Martin York Avatar answered Oct 03 '22 14:10

Martin York