1

我正在尝试将指针转换为 int(或 unsigned int),无论我尝试什么,它都不想工作。

我已经尝试过static_cast<intptr_t>(obj),reinterpret_cast<intptr_t>(obj)和 C 风格强制转换的各种组合, intptr_t's, unsigned int's, 我包括 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;
    // ...
}

他们都给出了完全相同的错误。

4

2 回答 2

6

你要么在一个平台上sizeof (Foo*) > sizeof (unsigned),要么你的编译器被设置为警告不可移植的代码。请注意,大多数 64 位编译器,包括 LP64 和 LLP64,都属于这一类。

不要求指针适合int. 这就是intptr_t.

如果您使用在 callbacls 期间仅提供用户上下文的第三方库int,您可以将索引传递到查找表中,因此指针本身存储在查找表中。这具有类型安全且不破坏别名假设的额外好处。

编辑:为我工作。(Comeau“tryitout”非常好用)

#include <stdint.h>

void myfunc(class Foo* obj)
{
    uintptr_t temp = reinterpret_cast<uintptr_t>(obj);
}

用于 ONLINE_EVALUATION_BETA2 的 Comeau C/C++ 4.3.10.1(2008 年 10 月 6 日 11:28:09) 版权所有 1988-2008 Comeau Computing。版权所有。模式:严格错误 C++ C++0x_extensions

“ComeauTest.c”,第 5 行:警告:变量“temp”已声明但从未引用 uintptr_t temp = 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;
}

用于 ONLINE_EVALUATION_BETA2 的 Comeau C/C++ 4.3.10.1(2008 年 10 月 6 日 11:28:09) 版权所有 1988-2008 Comeau Computing。版权所有。模式:严格错误 C90

“ComeauTest.c”,第 3 行:警告:声明在函数 void myfunc(struct Foo* obj) 之外不可见 ^

“ComeauTest.c”,第 5 行:警告:变量“temp”已声明但从未引用 uintptr_t temp = (uintptr_t)obj; ^

在严格模式下,使用 -tused,编译成功(但请记住,Comeau 在线编译器不会链接)。

于 2010-10-09T22:38:53.600 回答
1

当然,最好通过显式强制转换来掌握类型转换。之前的答案说得很好。

但我有一个绕过编译器的建议。有一个选项可以让编译器接受当前的精度损失:

gcc -fpermissive
于 2019-04-30T15:45:18.933 回答