Question

I have a problem with an OpenGL project, converting from a void* pointer to a shared_ptr<mytype>.

I am using Bullet to set pointers on the rigid body with:

root_physics->rigidBody->setUserPointer(&this->root_directory->handle);

The handle is of type shared_ptr<mytype>.

The void* pointer is returned by Bullet's library function, getUserPointer():

RayCallback.m_collisionObject->getUserPointer()

To convert back to mytype, static_cast is not working:

std::shared_ptr<disk_node> u_poi = static_cast< std::shared_ptr<disk_node> >( RayCallback.m_collisionObject->getUserPointer() );

The error, at compilation time:

/usr/include/c++/4.8/bits/shared_ptr_base.h:739:39: error: invalid conversion from ‘void*’ to ‘mytype*’ [-fpermissive]

Any idea how I can convert from the void* returned by getUserPointer() to shared_ptr<mytype>?

Was it helpful?

Solution

Since you are storing a pointer to an instance of std::shared_ptr you need to cast the value returned by getUserPointer to std::shared_ptr<>* instead of just std::shared_ptr<>.

std::shared_ptr<disk_node>* u_poi
  = static_cast< std::shared_ptr<disk_node>* >(RayCallback.m_collisionObject->getUserPointer());

OTHER TIPS

I think there a simpler way:

  1. change void* to disk_node*
  2. store disk_node* in shared_ptr.

Just like this:

std::shared_ptr<disk_node> u_poi =
     static_cast<disk_node*>(RayCallback.m_collisionObject->getUserPointer());

Solved: example:

using MyType = int;
std::shared_ptr<void> void_ptr = std::make_shared<MyType>(0);
std::shared_ptr<MyType> *p = reinterpret_cast<std::shared_ptr<MyType>*>(&void_ptr);//ok
std::shared_ptr<MyType> q = *p; //ok

you can write it in oneline:

auto q = *reinterpret_cast<std::shared_ptr<MyType>*>(&void_ptr); 

//failed below

std::shared_ptr<MyType> q =  reinterpret_cast<std::shared_ptr<MyType>>(void_ptr);

That's what reinterpret_cast is for:

reinterpret_cast<std::shared_ptr<disk_node>*>(RayCallback.m_collisionObject->getUserPointer());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top