ctypes NULL pointers; was: Python To Send Emails Via Outlook Express

Lenard Lindstrom len-1 at telus.net
Sun Jan 2 16:26:28 EST 2005

Posted in a previous thread was some Python code for accessing Window's
Simple MAPI api using the ctypes module.


This Simple MAPI module was Ian's completed version of an example
I had posted in an earlier message. In it I had to set some pointer
fields in a C structure to NULL. I was not happy with the solution I
used so I made an inquiry on the ctypes-users mailing list. Thanks to
Thomas Heller I got some answers.

The simplest way to create a NULL pointer instance in ctypes is to
call the pointer class without an argument.

from ctypes import POINTER, c_int
INT_P = POINTER(c_int)  # A pointer to a C integer
p = INT_P()  # An INT_P instance set to NULL

When the pointer is a member of a structure things are a little different.
For the ctypes primatives c_void_p, c_char_p and c_wchar_p one can simply
use None to set the field NULL.

from ctypes import Structure, c_void_p
class STRUCT(Structure):
    _fields_ = [('voidptr', c_void_p)]
s=STRUCT( None ) # Create an instance with voidptr field NULL

This is documented in the ctypes tutorial. A problem with ctypes 0.9.2
prevents using None to initialize POINTER derived fields. This has
been fixed so future releases will allow it. In the meantime the
following will work.

class IPSTRUCT(Structure):
    _fields_ [('intptr'), INT_P]

A null pointer of the correct type is assigned to the field. I hope this
clears up any confusion my Simple MAPI example may have caused regarding
ctypes pointers.

Lenard Lindstrom
<len-l at telus.net>

More information about the Python-list mailing list