Python CTypes translation of (pv != NULL)
Thomas Heller
theller at python.net
Wed Sep 27 14:22:47 EDT 2006
p.lavarre at ieee.org schrieb:
>> It says:
>>
>> NULL pointers have a False boolean value:
>> >>> null_ptr = POINTER(c_int)()
>> >>> print bool(null_ptr)
>> False
>
> Yes.
>
>> That means that NULL pointers are considered False in a boolean
>> expression (and you could assume that non-NULL pointers are True, as
>> any other object in general),
>
> I see this now that you show the clueless newbie me, yes thank you.
> Except now by showing me here we have provoked the authority Thomas
> Heller to say:
>
>> > > Generally pointer instances have a False boolean value, so
>> > > 'if pv: ....'
>> > > should work. Except for c_void_p, c_char_p and c_wchar_p instances.
>
> That English I do not understand. "Except" how?
Actually I was wrong - there is no exception. To summarize:
All ctypes NULL pointers have a False boolean value.
So, this C-code:
if (pv) { /* or 'if (pv != NULL)' */
return *pv; /* whatever */
} else {
/* handle NULL pointer */
}
translates to this Python code:
if pv:
return pv[0] # or whatever
else:
# pv is a NULL pointer
Works for instances of c_char_p, c_void_p, c_wchar_p,
and instances of POINTER(some_ctype).
If you want to make the 'if pv:' line more verbose, you could as well
write 'if bool(pv):' or 'if bool(pv) == False', but why would
you want to do this?
Thomas
More information about the Python-list
mailing list