boost::shared_ptr to void * and vice versa

Viewed 8920

I am developing an application in C, where I need to used a 3rd party C++ library. So, I am basically writing a wrapper around the C++ library to make it possible to call it from my application which is in pure C. Some of the methods in the library returns pointer of type boost::shared_ptr, which I need to cast to void* [for C] and then convert it back to boost::shared_ptr type to reuse it for further processing. I used the following ways to do the conversion:

To void* :

void * func1()
{
    //after the boost::shared_ptr is created
    return static_cast<void *> (SHARED_PTR.get())
}

From void* :

void func2(void * VOID_PTR) //VOID_PTR returned by func1
{
    boost::shared_ptr<T> SHARED_PTR = *(boost::shared_ptr <T> *)(VOID_PTR);
}

However, I am getting SIGSEGV in func2, which I believe is happening because the shared_ptr being deallocated because its ref-count getting 0.

I was looking for correct ways to do this conversion and suggestions from experts of the SO community.

Thanks in advance!

3 Answers

nowadays that shared_ptr is part of the standard library

std::shared_ptr<type> ptr;
auto ptr1 = reinterpret_cast<void *>(&ptr); /* shared_ptr > void ptr */
auto ptr2 = * reinterpret_cast(std::shared_ptr<type>*)(ptr1); /* void ptr > shared_ptr */

What to do depends on what the C library does with the void* pointer. If it at some point is used as a T* then that's what you need to pass, as you're doing. To get back a shared_ptr you then need T to implement boost::enable_shared_from_this, and call its shared_from_this member function, i.e. reinterpret_cast<T*>(void_ptr)->shared_from_this().

Related