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

David Rushby DavidRushby at gmail.com
Fri Jan 27 22:16:35 EST 2006


Alexander Schmolck wrote:
> 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)?

Do you really need to represent the pointers as integers, or do you
just need to pass them through Python and back to C?  If the latter,
how about using PyCObject_FromVoidPtr/PyCObject_AsVoidPtr
(http://docs.python.org/api/cObjects.html )?  PyCObject is probably
aimed squarely at the task you're doing (passing an opaque handle to a
C object from C into Python and back to C).

> 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)

I haven't actually done any Win64 programming, but I've read that on
that platform, sizeof(long) == 4, but sizeof(void *) == 8, so the C++
code above won't work on that platform.  BTW, Visual C++ 7 and 8 have a
helpful /Wp64 switch that'll emit Win64 portability warnings.




More information about the Python-list mailing list