Gasim
Gasim

Reputation: 7961

Is there a way to cast a shared ptr to void pointer and then cast the void pointer back to shared pointer?

I have a shared pointer of objects throughout my application. Here is one example:

std::shared_ptr<MyTexture> texture = loadImageFromFile("someFile.png");

I am using a UI library called ImGui and this library has a concept of a texture ID, which is a void pointer. I am currently passing the data to this library by doing the following:

ImGui::Image(texture.get());

And my backend stores these textures in a map that points to the Graphics API related data type (it is a Vulkan descriptor set but ) to be able to render the texture. Now, I have one particular issue about this. I want to manage this with a smart pointer. However, I am passing it as a raw pointer; so, I am not able to just wrap it in a shared pointer because the original shared pointer will be destroyed by this. Internally, I am using shared pointers everywhere except for this one particular case. Is there some way that I can pass a shared pointer object itself as raw void pointer and then cast it back to shared pointer; so, I do not lose the shared pointer counter when passing the pointer to this function?

Upvotes: 1

Views: 1585

Answers (1)

Top-Master
Top-Master

Reputation: 8745

No, not with std::shared_ptr, I mean, you can get raw-pointer from smart-pointer, but you simply can't get SAME-REF-COUNTER (wrapped in smart-pointer) from raw-pointer.

But you can:

  • Simply ensure your "void *" usage NEVER outlives the smart-pointer (else expect undefined-behaviour).
  • Or implement your own smart-pointer class, which has internal hash-map, that stores instances as value (with raw-pointer as key), and then later in a method finds and returns smart-pointer by "void *" input (like: static MySmartPtr fromRaw(void *)).
  • Or manually store std::shared_ptr in a hash-map (like above but without custom smart-pointer implemention).

Upvotes: 2

Related Questions