Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wrap a C++ function that returns a smart pointer in C?

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.

like image 535
Fijoy Vadakkumpadan Avatar asked Oct 13 '16 21:10

Fijoy Vadakkumpadan


1 Answers

You pretty much have to return an opaque pointer to the C code. So you'll need to use new to allocate a new smart pointer that you can return a pointer to.

About your only alternative is to use a collection of shared pointers to keep the object alive. When the C code indicates it's finished with the object, you remove the shared pointer from the collection. This allows you to return any kind of identifier you want to the C code -- it's just used as a handle to find the object in the collection.

like image 195
David Schwartz Avatar answered Oct 12 '22 12:10

David Schwartz