Converting Pointers to Integers for 64-Bit Compatibility
An existing codebase, originally designed for a 32-bit machine, employs a function with a void* argument that's subsequently converted to an appropriate type within the function:
void function(MESSAGE_ID id, void* param) { if(id == FOO) { int real_param = (int)param; // ... } }
When adapting this code to a 64-bit environment, the compiler flags an error:
error: cast from 'void*' to 'int' loses precision
To address this, a modification is required that maintains compatibility with 32-bit machines as well.
Solution
For a modern C approach, reinterpret_cast
#include <cstdint> void *p; auto i = reinterpret_cast<std::uintptr_t>(p);
Correct Integer Type for Pointer Storage
The recommended data type for storing pointers as integers is uintptr_t or intptr_t. These types reside in the
Appropriate Casting Operator
In C , reinterpret_cast is the preferred casting mechanism for this conversion. It replaces the C-style cast operator, which is no longer favored in C .
The above is the detailed content of How to Safely Convert Pointers to Integers for 64-Bit Compatibility?. For more information, please follow other related articles on the PHP Chinese website!