Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

types

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?

like image 381
Elsa Avatar asked Feb 24 '23 10:02

Elsa


2 Answers

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;
like image 106
Chris Jester-Young Avatar answered Mar 05 '23 21:03

Chris Jester-Young


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);
    // ...
}
like image 37
Michael Aaron Safyan Avatar answered Mar 05 '23 20:03

Michael Aaron Safyan