I have C code that calls C++ code. The C++ code creates an object and then passes it back to the C code, which stores the object in a struct:
extern "C" void cppFn(?** objectPtr)
{
*objectPtr = new Object();
}
void cFn()
{
THESTRUCT theStruct = {0};
cppFn(&(theStruct.objectPtr));
}
typedef struct THESTRUCT
{
?* objectPtr;
} THESTRUCT;
My question: what is the accepted type to use for objectPtr?
void
. Like so:
typedef struct THESTRUCT {
void* objectPtr;
} THESTRUCT;
void*
is a "generic" pointer type. (You have to cast it to some other type to use it. Since there is no type to cast it to at the C end, it's effectively an opaque pointer.)
Another approach is to make a forward declaration for your C++ type, without defining it (since that's impossible to do at the C end). So if your C++ type is called foo
, you could do:
struct foo;
typedef struct THESTRUCT {
struct foo* objectPtr;
} THESTRUCT;
You should use a 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);
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With