C Wrapper for C++

我怕爱的太早我们不能终老 提交于 2019-11-27 11:18:32

问题


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?


回答1:


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.




回答2:


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




回答3:


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




回答4:


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!



来源:https://stackoverflow.com/questions/7691035/c-wrapper-for-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!