Vicente Bolea
Vicente Bolea

Reputation: 1583

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.

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.

Upvotes: 5

Views: 800

Answers (3)

Loki Astari
Loki Astari

Reputation: 264729

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);
}

Upvotes: 6

Captain Obvlious
Captain Obvlious

Reputation: 20103

You need to create C compatible forwarding functions that take as their first parameter a pointer to the object. 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);
}

Upvotes: 5

Carl Norum
Carl Norum

Reputation: 225252

Write a C wrapper around your C++ interface. Compile it as C++, but make sure to include your C interface in an extern "C" block. This new interface should link fine with your C program and provide you with access to your C++ code.

Upvotes: 6

Related Questions