Search code examples
c++gcccasting64-bit32-bit

Converting a pointer into an integer


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

Of course, on a 64 bit machine, I get the error:

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

I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?


Solution

  • Use intptr_t and 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
    

    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.