将uint64_t转换为void *并返回

时间:2017-08-13 18:22:00

标签: c++ void-pointers reinterpret-cast static-cast

我正在尝试以下方法将句柄转换为void *,然后以下列方式返回句柄

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

但是,如果我这样做,我就能恢复hInt

uint64_t hIntBack = reinterpret_cast<uint64_t>(hPoint)

我不确定我是否理解这两种方法之间的区别。

1 个答案:

答案 0 :(得分:1)

在此代码中:

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

您实际上是在查看内存位置hPoint的值。这是因为您要将其转换为uint64_t *,然后抓取该位置的值。

作为旁注,虽然uint64_t适用于64位机器,但执行此类操作的标准方法是使用uintptr_t,它保证为您正在编译的体系结构的指针大小。如果您要在非XX位机器上使用uintXX_t编译代码,编译器将带来错误

相关问题