Ale*_*lex 0 c++ casting intptr
我正在尝试将指针强制转换为int(或unsigned int),无论我尝试什么它都不想工作.
我试过static_cast<intptr_t>(obj),reinterpret_cast<intptr_t>(obj)以及空调风格不同的组合铸就,intptr_t的,unsigned int的,和我包括stdint.h.从我读过的内容来看,我尝试过的很多东西中的一件应该可行.是什么赋予了?
我没有打扰包括代码,因为它正是我所描述的,但是既然你问过,我已经尝试了所有这些以及其他组合:
void myfunc(Foo* obj)
{
// ...
uintptr_t temp = reinterpret_cast<uintptr_t>(obj);
uintptr_t temp = static_cast<uintptr_t>(obj);
uintptr_t temp = (uintptr_t)obj;
intptr_t temp = reinterpret_cast<intptr_t>(obj);
intptr_t temp = static_cast<intptr_t>(obj);
intptr_t temp = (intptr_t)obj;
unsigned int temp = reinterpret_cast<unsigned int>(obj);
unsigned int temp = static_cast<unsigned int>(obj);
unsigned int temp = (unsigned int)obj;
// ...
}
Run Code Online (Sandbox Code Playgroud)
他们都给出完全相同的错误.
您要么在平台上sizeof (Foo*) > sizeof (unsigned),要么您的编译器设置为警告不可移植的代码.请注意,大多数64位编译器(LP64和LLP64)都属于此类别.
没有要求指针适合int.这就是重点intptr_t.
如果您使用的是第三方库,只提供了一个int用于callbacls在用户上下文,你可以传递一个索引查找表,使指针本身存储在查找表.这具有类型安全和不破坏别名假设的额外好处.
编辑:适合我.(Comeau"tryitout"非常方便)
#include <stdint.h>
void myfunc(class Foo* obj)
{
uintptr_t temp = reinterpret_cast<uintptr_t>(obj);
}
Run Code Online (Sandbox Code Playgroud)
Comeau C/C++ 4.3.10.1(2008年10月6日11:28:09)ONLINE_EVALUATION_BETA2版权所有1988-2008 Comeau Computing.版权所有.MODE:严格错误C++ C++ 0x_extensions
"ComeauTest.c",第5行:警告:变量 "TEMP" 被宣布,但从未uintptr_t的温度引用=的reinterpret_cast(OBJ);的reinterpret_cast(OBJ);
在严格模式下,使用-tused,编译成功(但请记住,Comeau在线编译器没有链接).编译启用C++ 0x扩展.
在C89模式下它也有效:
#include <stdint.h>
void myfunc(struct Foo* obj)
{
uintptr_t temp = (uintptr_t)obj;
}
Run Code Online (Sandbox Code Playgroud)
Comeau C/C++ 4.3.10.1(2008年10月6日11:28:09)ONLINE_EVALUATION_BETA2版权所有1988-2008 Comeau Computing.版权所有.MODE:严格错误C90
"ComeauTest.c",第3行:警告:声明不函数void MYFUNC(结构的Foo*OBJ)的外部可见^
"ComeauTest.c",第5行:警告:变量 "TEMP" 被宣布,但从未uintptr_t的温度=(uintptr_t的)参考OBJ; ^
在严格模式下,使用-tused,编译成功(但请记住,Comeau在线编译器没有链接).