[英]Cast to pointer from integer of different size (passing int as a const void * parameter)
I have to maintain a chunk of source code on Linux with gcc which has the following function prototype: 我必须使用gcc维护Linux上的大量源代码,该代码具有以下功能原型:
int foo(const void*, ...)
I have to pass an integer into this function. 我必须将一个整数传递给此函数。 I know that this is a bad idea but at this stage, I'm not allowed to modify the source code.
我知道这是个坏主意,但是在现阶段,我不允许修改源代码。
ie I have to call foo(n)
( n
is defined as int n
) 即我必须调用
foo(n)
( n
定义为int n
)
On a 64-bit machine, I get an error: 在64位计算机上,出现错误:
cast to pointer from integer of different size
As I understand, this is because the size of an integer on a 32-bit machine is four bytes while the size of a pointer to a void is eight bytes. 据我了解,这是因为32位计算机上整数的大小为4个字节,而指向void的指针的大小为8个字节。
I resolve the compilation error by first casting the integer with size 4 bytes to a long with size 8 bytes. 我通过首先将大小为4个字节的整数转换为大小为8个字节的long来解决编译错误。 So I did
foo((long)n)
所以我做了
foo((long)n)
I wonder if this is an acceptable way to deal with this issue or are there other suggestions? 我想知道这是否是解决此问题的可接受方法,或者还有其他建议吗?
You could use intptr_t
, but it is optional and may not be available in stdint.h
: 您可以使用
intptr_t
,但是它是可选的,可能在stdint.h
不可用:
intptr_t n = 1;
foo((void*)n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.