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.
Richard Corden
source share