ctypes.c_void_p(-1) might not be C return (void *) -1

p.lavarre at ieee.org p.lavarre at ieee.org
Thu Sep 28 19:25:43 CEST 2006

> Subject: Python CTypes translation of (pv != NULL)

And so then the next related Faq is:

Q: How should I test for ((void *) -1)?


(pv == 0xffffFFFF) works often.

(ctypes.cast(pv, ctypes.c_void_p).value == 0xffffFFFF) works better.

((void *) -1) appears often in 32-bit Windows, behind the name
INVALID_HANDLE_VALUE of the type HANDLE that is def'ed as the type
PVOID that is def'ed as (void *).  -1 is xffffFFFF in 32-bit two's

The more complex comparison works more often because specifying a
restype doesn't decide the __class__ of the result.  For example, the
run below shows a <type 'long'> result value passed back from a C
routine that has a c_void_p restype:

$ gcc -o passlib.so -dynamiclib -Wall passlib.c
$ python results.py
True False c_void_p(4294967295L) <class 'ctypes.c_void_p'>
True True 4294967295 <type 'long'>
$ cat passlib.c
void * passback(int ii)
        return (void *) ii;
$ cat results.py
from ctypes import *
passlib = cdll.LoadLibrary('./passlib.so')
passback = _fx = passlib.passback
_fx.restype = c_void_p
_fx.argtypes  = [c_int]
def test(pv):
    print cast(pv, c_void_p).value == 0xffffFFFF,
    print pv == 0xffffFFFF,
    print pv, pv.__class__

All true?  All bogus?  Partly bogus?  Curiously yours, Pat LaVarre

More information about the Python-list mailing list