CodeMonkey
CodeMonkey

Reputation: 12424

How can i cast between void* and boost shared ptr

I've got these lines:

typedef boost::shared_ptr<A> A_SPtr;
void *f(void* var){ ...

and i want to be able to do something like this:

A_SPtr instance = (void*)(var);

how can i do it? Also, how can i cast the other way around meaning from the shared_ptr to void*?

Upvotes: 4

Views: 5686

Answers (2)

David Schwartz
David Schwartz

Reputation: 182753

Just cast pointers to shared pointers to and from void *.

  1. shared_ptr to void *:

    f (reinterpret_cast<void *>;(&A_SPtr));
    
  2. void * back to shared_ptr:

    A_SPtr instance = * reinterpret_cast(boost::shared_ptr<A>*)(var);
    

CAUTION: This passes a pointer to the shared pointer to the thread. This will not work if the shared pointer does not remain in existence through the life of the thread function – otherwise, the thread will have a pointer to an object (the shared pointer) that no longer exists. If you cannot meet that requirement, pass a pointer to a new shared_ptr and delete it when the thread is done with it. (Or use boost:bind which works with shared pointers directly.)

Upvotes: 6

bames53
bames53

Reputation: 88155

As long as you're sure it's okay to assume ownership of the void* passed to you in f, that the void* does in fact refer to an A object, and you know the correct way to clean up, then you can just go ahead and use a smart pointer to assume ownership:

typedef boost::shared_ptr<A> A_SPtr;

void *f(void *var){
    A_SPtr instance(static_cast<A*>(var));
}

Edit: It's not clear from the question, but some comments indicate that your actually trying to pass a smart pointer through a 'generic' interface that uses void*. You do this the same way you'd do it for any type:

void *f(void *var){
    A_SPtr *instance = static_cast<A_SPtr *>(var);
}

And you pass the pointer like:

A_SPtr a;
f(&a);

As with any pointer you must ensure that the object's lifetime is sufficient for the pointer to be valid when f receives it.

Upvotes: 0

Related Questions