如何把 const void* 转换成 unsigned int?

在这段代码中:

unsigned int lptr = lua_topointer(L, -1);

它会出现这个错误: 无法将 'const void *' 转换为 'unsigned int'

我尝试使用 reinterpret_cast 进行转换,代码如下:

unsigned int lptr = reinterpret_cast<const void*>(lua_topointer(L, -1)));

但是它会再次报错,错误信息为: 无法将类型为 'const void *' 的值用于初始化类型为 'unsigned int' 的实体

如果有任何帮助,我将不胜感激。

点赞
用户114421
用户114421

lua_topointer 返回一个 void const*。你的 reinterpret_cast 实际上没有改变任何东西。你需要写的是:

unsigned int value = reinterpret_cast<unsigned int>(lua_topointer(L, -1)));

但请注意,这仅适用于大小与指针大小匹配的平台。最好使用 <cstdint> 中的 std::uintptr_t,因为大小是保证匹配的。

std::uintptr_t value = reinterpret_cast<std::uintptr_t>(lua_topointer(L, -1)));
2018-11-23 01:56:50
用户2079303
用户2079303

很难理解你说的将空指针转换为整数的意思。如果您想要访问指定的对象,则请参阅 lua_topointer 的文档:

将给定可接受索引处的值转换为通用 C 指针(void )。该值可以是 userdata、表、线程或函数;否则,lua_topointer 返回 NULL。不同的对象将给出不同的指针。*无法将指针转换回其原始值。 通常,此函数仅用于调试信息。

请注意,根据引用的文档,指定的对象不能是“无符号整型”。


如果您想要将指针表示为整数,首先建议您考虑“为什么”要这样做。通常不需要。大多数合理的使用整数表示的操作(如打印)可以直接使用指针本身完成。

但是,如果您真的想要“转换”指针为整数,则 unsigned int 不是一个好的选择,因为它不能保证能表示数据指针可以表示的所有值。 std::uintptr_t 可以表示所有这些值,这是正确的转换方法:

reinterpret_cast<std::uintptr_t>(data_pointer) 
2018-11-23 02:05:25