Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
Pedro Avatar asked Oct 07 '11 17:10

Pedro


People also ask

What is C wrapper?

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)

How do you wrap C in C++?

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.

Can C code use C++ library?

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.

Can C and C++ be mixed?

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.


2 Answers

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.

like image 146
Dark Falcon Avatar answered Nov 08 '22 04:11

Dark Falcon


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

like image 41
Hans-Christoph Steiner Avatar answered Nov 08 '22 05:11

Hans-Christoph Steiner