How to use c++ objects in c?

Give the C++ module a C interface:

magic.hpp:

struct Magic
{
    Magic(char const *, int);
    double work(int, int);
};

magic.cpp: (Implement Magic.)

magic_interface.h:

struct Magic;

#ifdef __cplusplus
extern "C" {
#endif

typedef Magic * MHandle;
MHandle create_magic(char const *, int);
void    free_magic(MHandle);
double  work_magic(MHandle, int, int);

#ifdef __cplusplus
}
#endif

magic_interface.cpp:

#include "magic_interface.h"
#include "magic.hpp"

extern "C"
{
    MHandle create_magic(char const * s, int n) { return new Magic(s, n); }
    void    free_magic(MHandle p) { delete p; }
    double  work_magic(MHandle p, int a, int b) { return p->work(a, b); }
}

Now a C program can #include "magic_interface.h" and use the code:

MHandle h = create_magic("Hello", 5);
double d = work_magic(h, 17, 29);
free_magic(h);

(You might even want to define MHandle as void * and add casts everywhere so as to avoid declaring struct Magic in the C header at all.)

Tags:

C++

C