将指针转换为整数 [英] Converting a pointer into an integer
问题描述
我正在尝试将现有代码改编为 64 位机器.主要问题是在一个函数中,前一个编码器使用了一个 void* 参数,该参数在函数本身中被转换为合适的类型.一个简短的例子:
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:
void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;
// ...
}
}
当然,在 64 位机器上,我得到错误:
Of course, on a 64 bit machine, I get the error:
error: cast from 'void*' to 'int' loses precision
我想更正这个问题,以便它仍然可以在 32 位机器上运行并且尽可能干净.有什么想法吗?
I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?
推荐答案
使用 intptr_t
和 uintptr_t
.
为确保以可移植的方式定义它,您可以使用如下代码:
To ensure it is defined in a portable way, you can use code like this:
#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 文件中,并在您需要的任何地方包含它.
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the stdint.h
file from here or use a portable one from here.
这篇关于将指针转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!