I need to wrap some APIs in a C++ library in C. I have done this in the past, using opaque pointers to class objects, extern "C", etc. as described here. However, this new library I'm dealing with makes extensive use of reference-counting smart pointers. I'm not sure how to do the wrapping in the presence of smart pointers. For example, let's say the C++ library has the following function:
SmartPointer<MyClass> foo() {
SmartPointer<MyClass> ret(new MyClass); // Create smart pointer ret
ret->DoSomething(); // Do something with ret
return ret;
}
How can I wrap foo()
in C? Clearly, I need an opaque pointer (like void*
or an empty struct pointer) that I can use in a C function to refer to the MyClass
object. The first option I thought of was to extract the MyClass
object from ret
, and cast it into a void*
. However, this void*
will become dangling once ret
goes out of scope due to the automatic deletion done by the smart pointer (correct me if I'm wrong).
The other option is to allocate a pointer to the smart pointer (say retPtr
), do *retPtr=ret
, and then create an opaque pointer to retPtr
. I think this option might work, but is this the best way?
Any help is appreciated.
ObjectType
? or does it just hold the pointer for a while and release it later? Also what is the relationship betweenObjectType
andMyClass
? – SororateMyClass *
, orSmartPointer<MyClass>
? – Sororate