Home > Backend Development > C++ > body text

How to Safely Convert Pointers to Integers for 64-Bit Compatibility?

Susan Sarandon
Release: 2024-11-17 06:06:04
Original
838 people have browsed it

How to Safely Convert Pointers to Integers for 64-Bit Compatibility?

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;
        // ...
    }
}
Copy after login

When adapting this code to a 64-bit environment, the compiler flags an error:

error: cast from 'void*' to 'int' loses precision
Copy after login

To address this, a modification is required that maintains compatibility with 32-bit machines as well.

Solution

For a modern C approach, reinterpret_cast serves as the ideal conversion mechanism. The code transforms as follows:

#include <cstdint>

void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);
Copy after login

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 header for C99 and the std namespace for C 11.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template