How to save a C ++ object in C code?

I have C code that calls C ++ code. C ++ code creates an object, and then passes it back to C code, which stores the object in a structure:

extern "C" void cppFn(?** objectPtr) { *objectPtr = new Object(); } void cFn() { THESTRUCT theStruct = {0}; cppFn(&(theStruct.objectPtr)); } typedef struct THESTRUCT { ?* objectPtr; } THESTRUCT; 

My question is: which acceptable type to use for objectPtr?

+4
source share
6 answers

void For instance:

 typedef struct THESTRUCT { void* objectPtr; } THESTRUCT; 

void* is the "generic" type of pointer. (You must give it to another type in order to use it. Since there is no type to give it to the end of C, it will be an effectively opaque pointer.)

Another approach is to make a direct declaration for your C ++ type without defining it (since this cannot be done at the end of C). Therefore, if your C ++ type is called foo , you can do:

 struct foo; typedef struct THESTRUCT { struct foo* objectPtr; } THESTRUCT; 
+6
source

You should use typedef to void* , as in:

 // C++ header class SomeObject { // ... }; // C header #ifdef __cplusplus # define EXTERNC extern "C" #else # define EXTERNC #endif typedef void* SomeObjectPtr; EXTERNC void cppFun(SomeObjectPtr); // C++ implementation of C header EXTERNC void cppFun(SomeObjectPtr untyped_ptr) { SomeObject* ptr = static_cast<SomeObject*>(untyped_ptr); // ... } 
+2
source

One solution is to save void* . You can try to save the correct type pointer, but C does not recognize this correct type, so you can just use void* , which means "any pointer".

0
source
 extern "C" void cppFn(void** objectPtr) { (Object*)(*objectPtr) = new Object(); } void cFn() { THESTRUCT theStruct = {0}; cppFn(&(theStruct.objectPtr)); } typedef struct THESTRUCT { void* objectPtr; } THESTRUCT; 
0
source

use void * for this purpose, since C will not know the exact type

void * - an easy way to store pointers of any type; so I guess this solution fits perfectly here

0
source

http://en.wikipedia.org/wiki/C%2B%2B11 Scroll down to “Modification to define plain old data”, I think you will find it useful. :-)

0
source

All Articles