Reputation: 7961
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
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:
void *
" usage NEVER outlives the smart-pointer (else expect undefined-behaviour).void *
" input (like: static MySmartPtr fromRaw(void *)
).std::shared_ptr
in a hash-map (like above but without custom smart-pointer implemention).Upvotes: 2