I'd like to use Pure Data as a prototyping tool for my own library. I found out that Pure Data patches are written开发者_StackOverflow 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?
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.
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...
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!
精彩评论