Elsa
Elsa

Reputation: 43

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

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?

Upvotes: 4

Views: 911

Answers (6)

The Floating Brain
The Floating Brain

Reputation: 956

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

Upvotes: 0

BiGYaN
BiGYaN

Reputation: 7159

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

void * is a simple way to store pointers of any type; so I guess this solution fits here nicely

Upvotes: 0

Tony Delroy
Tony Delroy

Reputation: 106096

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

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95499

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);
    // ...
}

Upvotes: 2

sharptooth
sharptooth

Reputation: 170499

One solution is to store void*. You could try to store the right type pointer, but C won't recognize that right type, so you can just use void* meaning "whatever pointer".

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223023

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;

Upvotes: 6

Related Questions