C Wrapper for C++

Pedro picture Pedro · Oct 7, 2011 · Viewed 18.9k times · Source

I'd like to use Pure Data as a prototyping tool for my own library. I found out that Pure Data patches are written in C, but my library is written in C++. So how can I use this code in pure data? Since I haven't used plain C, I'd like to know how I could write a C wrapper for C++ classes and how do instantiate my classes then? Or do I have to rewrite everything in C?

Answer

Dark Falcon picture Dark Falcon · Oct 7, 2011

You will need to write wrapper functions for every function which needs to be called. For example:

// The C++ implementation
class SomeObj { void func(int); };

extern "C" {
  SomeObj* newSomeObj() {return new SomeObj();}
  void freeSomeObj(SomeObj* obj) {delete obj;}
  void SomeObj_func(SomeObj* obj, int param) {obj->func(param)}
}

// The C interface
typedef struct SomeObjHandle SomeObj;

SomeObj* newSomeObj();
void freeSomeObj(SomeObj* obj);
void SomeObj_func(SomeObj* obj, int param);

Note this must be C++ code. The extern "C" specifies that the function uses the C naming conventions.