C Wrapper for C++

前端 未结 4 1310
心在旅途
心在旅途 2020-12-13 15:46

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

相关标签:
4条回答
  • 2020-12-13 16: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.

    0 讨论(0)
  • 2020-12-13 16:38

    Let me put it another way:

    1) You can call C functions, data and libraries from C++ source, and you call C++ source from C.

    2) Whenever C calls into C++ source, however, that source must be written in a C subset of C++.

    3) Part of this is using "extern C".

    4) Another part is using "#ifdef __cplusplus"

    5) The links I cited above give plenty of details

    6) I looked at the Pure Data site. You might have to make some "tweaks" to your library. You might wish to create a new header. But fundamentally, I think you can probably accomplish your goal of getting your library to integrate with Pure Data.

    IMHO...

    0 讨论(0)
  • 2020-12-13 16:41

    You can also write objects for Pure Data using C++ using the flext framework.

    0 讨论(0)
  • 2020-12-13 16:42

    You can absolutely call C from C++ - no problemo!

    Worst case, you might have to explicitly declare those functions you call from Pure Data as "extern C". But it's almost certain that Pure Data has already done that for you (you'll probably see "extern C" in the Pure Data header files.

    Here's more info:

    http://msdn.microsoft.com/en-us/library/0603949d%28v=vs.80%29.aspx

    'Hope that helps!

    0 讨论(0)
提交回复
热议问题