Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I store a uint32_t or uint64_t in a void pointer

I have a uint32_t (and in the future it might become uint64_t) variable. There is a function in one of the libraries that I use that allows passing a void pointer to it. How can I pass a uint32_t to this void pointer:

uint32_t myEntity = 1242242;
// not a pointer; so, error about invalid conversion
actor->userData = static_cast<void *>(myEntity);

I can’t use a pointer to this primitive type because the value can be coming from an argument or similar and since it is a uint, I don’t want to use references for it.

Is there some way that I can set this value into a void pointer; so that, I can then retrieve it the same way without creating a value in the heap for it to work properly. Otherwise, I will need to manage the destruction of the objects in order to not cause memory leaks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For what you are attempting, you need to use reinterpret_cast instead of static_cast, eg:

actor->userData = reinterpret_cast<void*>(myEntity);
...
myEntity = reinterpret_cast<uint32_t>(actor->userData);

Note, you mention that the value may be changed to a uint64_t in the future. Just note that you will have to compile your code for a 64bit build in that case (if you are not already), otherwise void* won’t be large enough to hold the value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading