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?
The C Wrapper provides access to RPC-based components from C applications and enables users to develop both clients and server. This section introduces the various possibilities for RPC-based client applications written in C. Using the C Wrapper in Single-threaded Environments (UNIX, Windows)
If you are including a C header file that isn't provided by the system, you may need to wrap the #include line in an extern "C" { /*... */ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.
Linking the Program Even if your program is primarily C code but makes use of C++ libraries, you need to link C++ runtime support libraries provided with the C++ compiler into your program. The easiest and best way to do that is to use CC , the C++ compiler driver, to do the linking.
C++ is a superset of C. Therefore, any valid C program is a valid C++ program, and there is no such thing as "mixing" C into C++. @Jonathan: int main() { int class = 2; } (valid C, not valid C++) C++ is not a superset of C; C and C++ share a common subset.
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.
You can also write objects for Pure Data using C++ using the flext framework.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With