0

I am trying the following approach to convert a handle to void* and then back to the handle the following way

uint64_t hInt = 154071804376; //assume this is a valid memory location

void* hPoint = reinterpret_cast<void*>(hInt);

uint64_t hIntBack = *static_cast<uint64_t*>(hPoint); unable to recover hInt here, getting some other number 140727986249696

However, if I do this, I am able to recover the hInt:

uint64_t hIntBack = reinterpret_cast<uint64_t>(hPoint)

I am not sure I understand the difference between the two approaches.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user3294816
  • 37
  • 1
  • 7
  • `void* hPoint = reinterpret_cast(hInt);` => `void* hPoint = reinterpret_cast(&hInt);` – user0042 Aug 13 '17 at 18:24
  • Similar question to https://stackoverflow.com/questions/45657427/access-violation-casting-to-void-and-back – M.M Aug 14 '17 at 01:35

1 Answers1

2

In this code:

uint64_t hIntBack = *static_cast<uint64_t*>(hPoint); unable to recover hInt here, getting some other number 140727986249696

You are actually looking at the value at the memory location hPoint. This is because you are converting it to a uint64_t *, then grabbing the value at that location.

As a side note, while uint64_t works fine for 64 bit machines, the standard way to do things like this is to use uintptr_t, which is guaranteed to be the size of a pointer for the architecture you're compiling for. If you were to compile the code with uintXX_t on a non XX-bit machine, the compiler will bring an error

Jordan
  • 358
  • 1
  • 9