简体   繁体   中英

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.

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

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

Since you mention that the value may be changed to a uint64_t in the future, just be aware that you will have to compile your code into a 64bit executable in that case (if you are not already), otherwise void* won't be large enough values that exceed the highest uint32_t value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM