C ++ code and objects from C?

Is there an easy way to work with C ++ objects directly from C? I want to expose some classes from C ++ to C or to FFI (external function interface). Of course, I can write such material:

class Foo{ .... }; void *make_foo(...){ Foo *ptr = new Foo(..) return static_cast<void *>(ptr); } .. int *foo_method1(void *fooptr, ...){ Foo *ptr = static_cast<Foo*>(fooptr); } 

But is there a simpler method?

+7
c ++ c lisp
source share
5 answers

This is, generally speaking, the easiest method.

Remember that you also need to use extern "C" for all of your C shell methods.

+8
source share

You are almost there. Prefix your standalone functions with extern "C" to disable the C ++ name mangling compiler.

For example:

 extern "C" void *make_foo(...){ Foo *ptr = new Foo(..) return static_cast<void *>(ptr); } 
+7
source share

Actually not the easiest way to do this. You can use SWIG to switch to another language with user-defined types that are more than a collection of data but are converted to C, you will need to use the idea of ​​C objects.

+1
source share

You can use Verrazano / Fetter to generate CFFI for C ++ code. But that requires GCC-XML, and I'm not sure about its portability.

+1
source share

If possible, then your classes are derived from the structure. Then you can use pointers to this structure in C code:

 // C++ code extern "C" struct Cfoo {}; extern "C" struct Cbar {}; class foo : public Cfoo {}; class bar : public Cbar {}; // C API extern "C" { struct Cfoo; struct Cbar; } 

This is not strictly a mistake, but gcc at least warns of conversion between pointers with different types.

 void foo (void) { struct Cfoo * pf; struct Cbar * pb; pf = pb; // gcc warns } 

If you cannot inherit, use a similar idea, but the C structure has a pointer to a C ++ object, and again just declare the structures in the C API again:

 // C++ code class foo {}; class bar {}; extern "C" struct Cfoo { foo * pFoo; }; extern "C" struct Cbar { bar * pBar; }; // C API extern "C" { struct Cfoo; struct Cbar; } 

The disadvantage here is that you must consider the lifetime of the Cfoo and Cbar objects.

+1
source share

All Articles