Alex Rivera | Logout

C Wrapper for C++

Asked 2011-10-07T17:57:31.417
21

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?

Edit
Report

1 Answer

34

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.

answered 2011-10-07T18:04:30.990

Your Answer