py-ext: casting pointers to ints on 32bit and 64bit systems

Alexander Schmolck a.schmolck at gmail.com
Fri Jan 27 18:00:33 EST 2006


what's the best approach to write C(++)-extension code that has to create a
python int from a C pointer and vice versa so that it works smoothly on 32 bit
and 64 platforms (on which sizeof(int) != sizeof(*void)) equally work (under
unix,mac&windows and with gcc, vc and borland)?

Currently the relevant code (in mlabraw.cpp available from
<http://mlabwrap.sf.net>) looks like somthing like this:

    /* C++ -> py */
    Engine *ep;
    [...]
    return Py_BuildValue("i", int(ep))

and this:

    /* py -> C++ */
    int lHandle;
    [...]
    PyArg_ParseTuple(args, "is:get", &lHandle, &lName)

I've suggested modifications along the following lines to a user who had
problems building the module on a 64 bit system

    /* C++ -> py */
    Engine *ep;
    [...]
    return Py_BuildValue("l", long(ep))

    /* py -> C++ */
    long lHandle;
    [...]
    PyArg_ParseTuple(args, "ls:get", &lHandle, &lName)

This apparently works, so I'm now looking for the best way to adapt the source
code so that it will (ideally) compile out of the box on both 32 bit and 64
bit systems.

I guess the right type to use would be intptr_t (rather than #define something
to be int or long according to platform), but I don't know how well that is
supported by various C++ compilers. Also, is there something better than

#ifdef _A_64_BIT_PLATFORM
    PyArg_ParseTuple(args, "ls:get", &lHandle, &lName)
#else
    PyArg_ParseTuple(args, "is:get", &lHandle, &lName)
#endif
?

and how would I best go about #define'ing _A_64_BIT_PLATFORM?

thanks,

'as



More information about the Python-list mailing list