Search code examples
c++cwrapperpuredata

C Wrapper for C++


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?


Solution

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