将指针转换为整数

新手上路,请多包涵

我正在尝试使现有代码适应 64 位机器。主要问题是在一个函数中,前面的编码器使用了一个 void* 参数,该参数在函数本身中被转换为合适的类型。一个简短的例子:

 void function(MESSAGE_ID id, void* param)
{
    if(id == FOO) {
        int real_param = (int)param;
        // ...
    }
}

当然,在 64 位机器上,我得到了错误:

 error: cast from 'void*' to 'int' loses precision

我想更正此问题,以便它仍然可以在 32 位机器上运行,并且尽可能干净。任何想法 ?

原文由 PierreBdR 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 928
2 个回答

使用 intptr_tuintptr_t

为了确保它以可移植的方式定义,您可以使用如下代码:

 #if defined(__BORLANDC__)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
    typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
#else
    #include <stdint.h>
#endif

只需将其放在某个 .h 文件中并包含在您需要的任何地方。

或者,您可以从 此处 使用便携式文件。

原文由 Milan Babuškov 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于 C++11,对于它的价值,假设您没有任何标题,然后定义:

 template<bool B, class T, class F> struct cond { typedef T type; };
template<class T, class F> struct cond<false, T, F> { typedef F type;};
static constexpr unsigned int PS = sizeof (void *);

using uintptr_type = typename cond<
   PS==sizeof(unsigned short), unsigned short ,
      typename cond<
          PS==sizeof(unsigned int), unsigned int,
              typename cond<
                  PS==sizeof(unsigned long), unsigned long, unsigned long long>::type>::type>::type;

之后,您可以执行以下操作:

 static uintptr_type ptr_to_int(const void *pointer) {
    return reinterpret_cast<uintptr_type>(pointer);
}
static void *int_to_ptr(uintptr_type integer) {
    return reinterpret_cast<void *>(integer);
}

原文由 Tomer Shalev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏