blob: d3661ab40f6f40cdaefaa1451b5d20c906b23609 [file] [log] [blame]
Fred Drakecc8f44b2001-08-20 19:30:29 +00001\chapter{Extending Python with C or \Cpp{} \label{intro}}
2
3
4It is quite easy to add new built-in modules to Python, if you know
5how to program in C. Such \dfn{extension modules} can do two things
6that can't be done directly in Python: they can implement new built-in
7object types, and they can call C library functions and system calls.
8
9To support extensions, the Python API (Application Programmers
10Interface) defines a set of functions, macros and variables that
11provide access to most aspects of the Python run-time system. The
12Python API is incorporated in a C source file by including the header
13\code{"Python.h"}.
14
15The compilation of an extension module depends on its intended use as
16well as on your system setup; details are given in later chapters.
17
18
19\section{A Simple Example
20 \label{simpleExample}}
21
22Let's create an extension module called \samp{spam} (the favorite food
23of Monty Python fans...) and let's say we want to create a Python
24interface to the C library function \cfunction{system()}.\footnote{An
25interface for this function already exists in the standard module
26\module{os} --- it was chosen as a simple and straightfoward example.}
27This function takes a null-terminated character string as argument and
28returns an integer. We want this function to be callable from Python
29as follows:
30
31\begin{verbatim}
32>>> import spam
33>>> status = spam.system("ls -l")
34\end{verbatim}
35
36Begin by creating a file \file{spammodule.c}. (Historically, if a
37module is called \samp{spam}, the C file containing its implementation
38is called \file{spammodule.c}; if the module name is very long, like
39\samp{spammify}, the module name can be just \file{spammify.c}.)
40
41The first line of our file can be:
42
43\begin{verbatim}
44#include <Python.h>
45\end{verbatim}
46
47which pulls in the Python API (you can add a comment describing the
48purpose of the module and a copyright notice if you like).
Fred Drake396ca572001-09-06 16:30:30 +000049Since Python may define some pre-processor definitions which affect
50the standard headers on some systems, you must include \file{Python.h}
51before any standard headers are included.
Fred Drakecc8f44b2001-08-20 19:30:29 +000052
Fred Drake396ca572001-09-06 16:30:30 +000053All user-visible symbols defined by \file{Python.h} have a prefix of
Fred Drakecc8f44b2001-08-20 19:30:29 +000054\samp{Py} or \samp{PY}, except those defined in standard header files.
55For convenience, and since they are used extensively by the Python
56interpreter, \code{"Python.h"} includes a few standard header files:
57\code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and
58\code{<stdlib.h>}. If the latter header file does not exist on your
59system, it declares the functions \cfunction{malloc()},
60\cfunction{free()} and \cfunction{realloc()} directly.
61
62The next thing we add to our module file is the C function that will
63be called when the Python expression \samp{spam.system(\var{string})}
64is evaluated (we'll see shortly how it ends up being called):
65
66\begin{verbatim}
67static PyObject *
68spam_system(self, args)
69 PyObject *self;
70 PyObject *args;
71{
72 char *command;
73 int sts;
74
75 if (!PyArg_ParseTuple(args, "s", &command))
76 return NULL;
77 sts = system(command);
78 return Py_BuildValue("i", sts);
79}
80\end{verbatim}
81
82There is a straightforward translation from the argument list in
83Python (for example, the single expression \code{"ls -l"}) to the
84arguments passed to the C function. The C function always has two
85arguments, conventionally named \var{self} and \var{args}.
86
87The \var{self} argument is only used when the C function implements a
88built-in method, not a function. In the example, \var{self} will
89always be a \NULL{} pointer, since we are defining a function, not a
90method. (This is done so that the interpreter doesn't have to
91understand two different types of C functions.)
92
93The \var{args} argument will be a pointer to a Python tuple object
94containing the arguments. Each item of the tuple corresponds to an
95argument in the call's argument list. The arguments are Python
96objects --- in order to do anything with them in our C function we have
97to convert them to C values. The function \cfunction{PyArg_ParseTuple()}
98in the Python API checks the argument types and converts them to C
99values. It uses a template string to determine the required types of
100the arguments as well as the types of the C variables into which to
101store the converted values. More about this later.
102
103\cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have
104the right type and its components have been stored in the variables
105whose addresses are passed. It returns false (zero) if an invalid
106argument list was passed. In the latter case it also raises an
107appropriate exception so the calling function can return
108\NULL{} immediately (as we saw in the example).
109
110
111\section{Intermezzo: Errors and Exceptions
112 \label{errors}}
113
114An important convention throughout the Python interpreter is the
115following: when a function fails, it should set an exception condition
116and return an error value (usually a \NULL{} pointer). Exceptions
117are stored in a static global variable inside the interpreter; if this
118variable is \NULL{} no exception has occurred. A second global
119variable stores the ``associated value'' of the exception (the second
120argument to \keyword{raise}). A third variable contains the stack
121traceback in case the error originated in Python code. These three
122variables are the C equivalents of the Python variables
123\code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see
124the section on module \module{sys} in the
125\citetitle[../lib/lib.html]{Python Library Reference}). It is
126important to know about them to understand how errors are passed
127around.
128
129The Python API defines a number of functions to set various types of
130exceptions.
131
132The most common one is \cfunction{PyErr_SetString()}. Its arguments
133are an exception object and a C string. The exception object is
134usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The
135C string indicates the cause of the error and is converted to a
136Python string object and stored as the ``associated value'' of the
137exception.
138
139Another useful function is \cfunction{PyErr_SetFromErrno()}, which only
140takes an exception argument and constructs the associated value by
141inspection of the global variable \cdata{errno}. The most
142general function is \cfunction{PyErr_SetObject()}, which takes two object
143arguments, the exception and its associated value. You don't need to
144\cfunction{Py_INCREF()} the objects passed to any of these functions.
145
146You can test non-destructively whether an exception has been set with
147\cfunction{PyErr_Occurred()}. This returns the current exception object,
148or \NULL{} if no exception has occurred. You normally don't need
149to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a
150function call, since you should be able to tell from the return value.
151
152When a function \var{f} that calls another function \var{g} detects
153that the latter fails, \var{f} should itself return an error value
154(usually \NULL{} or \code{-1}). It should \emph{not} call one of the
155\cfunction{PyErr_*()} functions --- one has already been called by \var{g}.
156\var{f}'s caller is then supposed to also return an error indication
157to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()},
158and so on --- the most detailed cause of the error was already
159reported by the function that first detected it. Once the error
160reaches the Python interpreter's main loop, this aborts the currently
161executing Python code and tries to find an exception handler specified
162by the Python programmer.
163
164(There are situations where a module can actually give a more detailed
165error message by calling another \cfunction{PyErr_*()} function, and in
166such cases it is fine to do so. As a general rule, however, this is
167not necessary, and can cause information about the cause of the error
168to be lost: most operations can fail for a variety of reasons.)
169
170To ignore an exception set by a function call that failed, the exception
171condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}.
172The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't
173want to pass the error on to the interpreter but wants to handle it
174completely by itself (possibly by trying something else, or pretending
175nothing went wrong).
176
177Every failing \cfunction{malloc()} call must be turned into an
178exception --- the direct caller of \cfunction{malloc()} (or
179\cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and
180return a failure indicator itself. All the object-creating functions
181(for example, \cfunction{PyInt_FromLong()}) already do this, so this
182note is only relevant to those who call \cfunction{malloc()} directly.
183
184Also note that, with the important exception of
185\cfunction{PyArg_ParseTuple()} and friends, functions that return an
186integer status usually return a positive value or zero for success and
187\code{-1} for failure, like \UNIX{} system calls.
188
189Finally, be careful to clean up garbage (by making
190\cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects
191you have already created) when you return an error indicator!
192
193The choice of which exception to raise is entirely yours. There are
194predeclared C objects corresponding to all built-in Python exceptions,
195such as \cdata{PyExc_ZeroDivisionError}, which you can use directly.
196Of course, you should choose exceptions wisely --- don't use
197\cdata{PyExc_TypeError} to mean that a file couldn't be opened (that
198should probably be \cdata{PyExc_IOError}). If something's wrong with
199the argument list, the \cfunction{PyArg_ParseTuple()} function usually
200raises \cdata{PyExc_TypeError}. If you have an argument whose value
201must be in a particular range or must satisfy other conditions,
202\cdata{PyExc_ValueError} is appropriate.
203
204You can also define a new exception that is unique to your module.
205For this, you usually declare a static object variable at the
206beginning of your file:
207
208\begin{verbatim}
209static PyObject *SpamError;
210\end{verbatim}
211
212and initialize it in your module's initialization function
213(\cfunction{initspam()}) with an exception object (leaving out
214the error checking for now):
215
216\begin{verbatim}
217void
218initspam()
219{
220 PyObject *m, *d;
221
222 m = Py_InitModule("spam", SpamMethods);
223 d = PyModule_GetDict(m);
224 SpamError = PyErr_NewException("spam.error", NULL, NULL);
225 PyDict_SetItemString(d, "error", SpamError);
226}
227\end{verbatim}
228
229Note that the Python name for the exception object is
230\exception{spam.error}. The \cfunction{PyErr_NewException()} function
231may create a class with the base class being \exception{Exception}
232(unless another class is passed in instead of \NULL), described in the
233\citetitle[../lib/lib.html]{Python Library Reference} under ``Built-in
234Exceptions.''
235
236Note also that the \cdata{SpamError} variable retains a reference to
237the newly created exception class; this is intentional! Since the
238exception could be removed from the module by external code, an owned
239reference to the class is needed to ensure that it will not be
240discarded, causing \cdata{SpamError} to become a dangling pointer.
241Should it become a dangling pointer, C code which raises the exception
242could cause a core dump or other unintended side effects.
243
244
245\section{Back to the Example
246 \label{backToExample}}
247
248Going back to our example function, you should now be able to
249understand this statement:
250
251\begin{verbatim}
252 if (!PyArg_ParseTuple(args, "s", &command))
253 return NULL;
254\end{verbatim}
255
256It returns \NULL{} (the error indicator for functions returning
257object pointers) if an error is detected in the argument list, relying
258on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the
259string value of the argument has been copied to the local variable
260\cdata{command}. This is a pointer assignment and you are not supposed
261to modify the string to which it points (so in Standard C, the variable
262\cdata{command} should properly be declared as \samp{const char
263*command}).
264
265The next statement is a call to the \UNIX{} function
266\cfunction{system()}, passing it the string we just got from
267\cfunction{PyArg_ParseTuple()}:
268
269\begin{verbatim}
270 sts = system(command);
271\end{verbatim}
272
273Our \function{spam.system()} function must return the value of
274\cdata{sts} as a Python object. This is done using the function
275\cfunction{Py_BuildValue()}, which is something like the inverse of
276\cfunction{PyArg_ParseTuple()}: it takes a format string and an
277arbitrary number of C values, and returns a new Python object.
278More info on \cfunction{Py_BuildValue()} is given later.
279
280\begin{verbatim}
281 return Py_BuildValue("i", sts);
282\end{verbatim}
283
284In this case, it will return an integer object. (Yes, even integers
285are objects on the heap in Python!)
286
287If you have a C function that returns no useful argument (a function
288returning \ctype{void}), the corresponding Python function must return
289\code{None}. You need this idiom to do so:
290
291\begin{verbatim}
292 Py_INCREF(Py_None);
293 return Py_None;
294\end{verbatim}
295
296\cdata{Py_None} is the C name for the special Python object
297\code{None}. It is a genuine Python object rather than a \NULL{}
298pointer, which means ``error'' in most contexts, as we have seen.
299
300
301\section{The Module's Method Table and Initialization Function
302 \label{methodTable}}
303
304I promised to show how \cfunction{spam_system()} is called from Python
305programs. First, we need to list its name and address in a ``method
306table'':
307
308\begin{verbatim}
309static PyMethodDef SpamMethods[] = {
310 ...
311 {"system", spam_system, METH_VARARGS},
312 ...
313 {NULL, NULL} /* Sentinel */
314};
315\end{verbatim}
316
317Note the third entry (\samp{METH_VARARGS}). This is a flag telling
318the interpreter the calling convention to be used for the C
319function. It should normally always be \samp{METH_VARARGS} or
320\samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an
321obsolete variant of \cfunction{PyArg_ParseTuple()} is used.
322
323When using only \samp{METH_VARARGS}, the function should expect
324the Python-level parameters to be passed in as a tuple acceptable for
325parsing via \cfunction{PyArg_ParseTuple()}; more information on this
326function is provided below.
327
328The \constant{METH_KEYWORDS} bit may be set in the third field if
329keyword arguments should be passed to the function. In this case, the
330C function should accept a third \samp{PyObject *} parameter which
331will be a dictionary of keywords. Use
332\cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to
333such a function.
334
335The method table must be passed to the interpreter in the module's
336initialization function. The initialization function must be named
337\cfunction{init\var{name}()}, where \var{name} is the name of the
338module, and should be the only non-\keyword{static} item defined in
339the module file:
340
341\begin{verbatim}
342void
343initspam()
344{
345 (void) Py_InitModule("spam", SpamMethods);
346}
347\end{verbatim}
348
349Note that for \Cpp, this method must be declared \code{extern "C"}.
350
351When the Python program imports module \module{spam} for the first
352time, \cfunction{initspam()} is called. (See below for comments about
353embedding Python.) It calls
354\cfunction{Py_InitModule()}, which creates a ``module object'' (which
355is inserted in the dictionary \code{sys.modules} under the key
356\code{"spam"}), and inserts built-in function objects into the newly
357created module based upon the table (an array of \ctype{PyMethodDef}
358structures) that was passed as its second argument.
359\cfunction{Py_InitModule()} returns a pointer to the module object
360that it creates (which is unused here). It aborts with a fatal error
361if the module could not be initialized satisfactorily, so the caller
362doesn't need to check for errors.
363
364When embedding Python, the \cfunction{initspam()} function is not
365called automatically unless there's an entry in the
366\cdata{_PyImport_Inittab} table. The easiest way to handle this is to
367statically initialize your statically-linked modules by directly
368calling \cfunction{initspam()} after the call to
369\cfunction{Py_Initialize()} or \cfunction{PyMac_Initialize()}:
370
371\begin{verbatim}
372int main(int argc, char **argv)
373{
374 /* Pass argv[0] to the Python interpreter */
375 Py_SetProgramName(argv[0]);
376
377 /* Initialize the Python interpreter. Required. */
378 Py_Initialize();
379
380 /* Add a static module */
381 initspam();
382\end{verbatim}
383
384An example may be found in the file \file{Demo/embed/demo.c} in the
385Python source distribution.
386
387\strong{Note:} Removing entries from \code{sys.modules} or importing
388compiled modules into multiple interpreters within a process (or
389following a \cfunction{fork()} without an intervening
390\cfunction{exec()}) can create problems for some extension modules.
391Extension module authors should exercise caution when initializing
392internal data structures.
393Note also that the \function{reload()} function can be used with
394extension modules, and will call the module initialization function
395(\cfunction{initspam()} in the example), but will not load the module
396again if it was loaded from a dynamically loadable object file
397(\file{.so} on \UNIX, \file{.dll} on Windows).
398
399A more substantial example module is included in the Python source
400distribution as \file{Modules/xxmodule.c}. This file may be used as a
401template or simply read as an example. The \program{modulator.py}
402script included in the source distribution or Windows install provides
403a simple graphical user interface for declaring the functions and
404objects which a module should implement, and can generate a template
405which can be filled in. The script lives in the
406\file{Tools/modulator/} directory; see the \file{README} file there
407for more information.
408
409
410\section{Compilation and Linkage
411 \label{compilation}}
412
413There are two more things to do before you can use your new extension:
414compiling and linking it with the Python system. If you use dynamic
415loading, the details depend on the style of dynamic loading your
416system uses; see the chapters about building extension modules on
417\UNIX{} (chapter \ref{building-on-unix}) and Windows (chapter
418\ref{building-on-windows}) for more information about this.
419% XXX Add information about MacOS
420
421If you can't use dynamic loading, or if you want to make your module a
422permanent part of the Python interpreter, you will have to change the
423configuration setup and rebuild the interpreter. Luckily, this is
424very simple: just place your file (\file{spammodule.c} for example) in
425the \file{Modules/} directory of an unpacked source distribution, add
426a line to the file \file{Modules/Setup.local} describing your file:
427
428\begin{verbatim}
429spam spammodule.o
430\end{verbatim}
431
432and rebuild the interpreter by running \program{make} in the toplevel
433directory. You can also run \program{make} in the \file{Modules/}
434subdirectory, but then you must first rebuild \file{Makefile}
435there by running `\program{make} Makefile'. (This is necessary each
436time you change the \file{Setup} file.)
437
438If your module requires additional libraries to link with, these can
439be listed on the line in the configuration file as well, for instance:
440
441\begin{verbatim}
442spam spammodule.o -lX11
443\end{verbatim}
444
445\section{Calling Python Functions from C
446 \label{callingPython}}
447
448So far we have concentrated on making C functions callable from
449Python. The reverse is also useful: calling Python functions from C.
450This is especially the case for libraries that support so-called
451``callback'' functions. If a C interface makes use of callbacks, the
452equivalent Python often needs to provide a callback mechanism to the
453Python programmer; the implementation will require calling the Python
454callback functions from a C callback. Other uses are also imaginable.
455
456Fortunately, the Python interpreter is easily called recursively, and
457there is a standard interface to call a Python function. (I won't
458dwell on how to call the Python parser with a particular string as
459input --- if you're interested, have a look at the implementation of
460the \programopt{-c} command line option in \file{Python/pythonmain.c}
461from the Python source code.)
462
463Calling a Python function is easy. First, the Python program must
464somehow pass you the Python function object. You should provide a
465function (or some other interface) to do this. When this function is
466called, save a pointer to the Python function object (be careful to
467\cfunction{Py_INCREF()} it!) in a global variable --- or wherever you
468see fit. For example, the following function might be part of a module
469definition:
470
471\begin{verbatim}
472static PyObject *my_callback = NULL;
473
474static PyObject *
475my_set_callback(dummy, args)
476 PyObject *dummy, *args;
477{
478 PyObject *result = NULL;
479 PyObject *temp;
480
481 if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
482 if (!PyCallable_Check(temp)) {
483 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
484 return NULL;
485 }
486 Py_XINCREF(temp); /* Add a reference to new callback */
487 Py_XDECREF(my_callback); /* Dispose of previous callback */
488 my_callback = temp; /* Remember new callback */
489 /* Boilerplate to return "None" */
490 Py_INCREF(Py_None);
491 result = Py_None;
492 }
493 return result;
494}
495\end{verbatim}
496
497This function must be registered with the interpreter using the
498\constant{METH_VARARGS} flag; this is described in section
499\ref{methodTable}, ``The Module's Method Table and Initialization
500Function.'' The \cfunction{PyArg_ParseTuple()} function and its
501arguments are documented in section \ref{parseTuple}, ``Extracting
502Parameters in Extension Functions.''
503
504The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()}
505increment/decrement the reference count of an object and are safe in
506the presence of \NULL{} pointers (but note that \var{temp} will not be
507\NULL{} in this context). More info on them in section
508\ref{refcounts}, ``Reference Counts.''
509
510Later, when it is time to call the function, you call the C function
511\cfunction{PyEval_CallObject()}. This function has two arguments, both
512pointers to arbitrary Python objects: the Python function, and the
513argument list. The argument list must always be a tuple object, whose
514length is the number of arguments. To call the Python function with
515no arguments, pass an empty tuple; to call it with one argument, pass
516a singleton tuple. \cfunction{Py_BuildValue()} returns a tuple when its
517format string consists of zero or more format codes between
518parentheses. For example:
519
520\begin{verbatim}
521 int arg;
522 PyObject *arglist;
523 PyObject *result;
524 ...
525 arg = 123;
526 ...
527 /* Time to call the callback */
528 arglist = Py_BuildValue("(i)", arg);
529 result = PyEval_CallObject(my_callback, arglist);
530 Py_DECREF(arglist);
531\end{verbatim}
532
533\cfunction{PyEval_CallObject()} returns a Python object pointer: this is
534the return value of the Python function. \cfunction{PyEval_CallObject()} is
535``reference-count-neutral'' with respect to its arguments. In the
536example a new tuple was created to serve as the argument list, which
537is \cfunction{Py_DECREF()}-ed immediately after the call.
538
539The return value of \cfunction{PyEval_CallObject()} is ``new'': either it
540is a brand new object, or it is an existing object whose reference
541count has been incremented. So, unless you want to save it in a
542global variable, you should somehow \cfunction{Py_DECREF()} the result,
543even (especially!) if you are not interested in its value.
544
545Before you do this, however, it is important to check that the return
546value isn't \NULL{}. If it is, the Python function terminated by
547raising an exception. If the C code that called
548\cfunction{PyEval_CallObject()} is called from Python, it should now
549return an error indication to its Python caller, so the interpreter
550can print a stack trace, or the calling Python code can handle the
551exception. If this is not possible or desirable, the exception should
552be cleared by calling \cfunction{PyErr_Clear()}. For example:
553
554\begin{verbatim}
555 if (result == NULL)
556 return NULL; /* Pass error back */
557 ...use result...
558 Py_DECREF(result);
559\end{verbatim}
560
561Depending on the desired interface to the Python callback function,
562you may also have to provide an argument list to
563\cfunction{PyEval_CallObject()}. In some cases the argument list is
564also provided by the Python program, through the same interface that
565specified the callback function. It can then be saved and used in the
566same manner as the function object. In other cases, you may have to
567construct a new tuple to pass as the argument list. The simplest way
568to do this is to call \cfunction{Py_BuildValue()}. For example, if
569you want to pass an integral event code, you might use the following
570code:
571
572\begin{verbatim}
573 PyObject *arglist;
574 ...
575 arglist = Py_BuildValue("(l)", eventcode);
576 result = PyEval_CallObject(my_callback, arglist);
577 Py_DECREF(arglist);
578 if (result == NULL)
579 return NULL; /* Pass error back */
580 /* Here maybe use the result */
581 Py_DECREF(result);
582\end{verbatim}
583
584Note the placement of \samp{Py_DECREF(arglist)} immediately after the
585call, before the error check! Also note that strictly spoken this
586code is not complete: \cfunction{Py_BuildValue()} may run out of
587memory, and this should be checked.
588
589
590\section{Extracting Parameters in Extension Functions
591 \label{parseTuple}}
592
593The \cfunction{PyArg_ParseTuple()} function is declared as follows:
594
595\begin{verbatim}
596int PyArg_ParseTuple(PyObject *arg, char *format, ...);
597\end{verbatim}
598
599The \var{arg} argument must be a tuple object containing an argument
600list passed from Python to a C function. The \var{format} argument
601must be a format string, whose syntax is explained below. The
602remaining arguments must be addresses of variables whose type is
603determined by the format string. For the conversion to succeed, the
604\var{arg} object must match the format and the format must be
605exhausted. On success, \cfunction{PyArg_ParseTuple()} returns true,
606otherwise it returns false and raises an appropriate exception.
607
608Note that while \cfunction{PyArg_ParseTuple()} checks that the Python
609arguments have the required types, it cannot check the validity of the
610addresses of C variables passed to the call: if you make mistakes
611there, your code will probably crash or at least overwrite random bits
612in memory. So be careful!
613
614A format string consists of zero or more ``format units''. A format
615unit describes one Python object; it is usually a single character or
616a parenthesized sequence of format units. With a few exceptions, a
617format unit that is not a parenthesized sequence normally corresponds
618to a single address argument to \cfunction{PyArg_ParseTuple()}. In the
619following description, the quoted form is the format unit; the entry
620in (round) parentheses is the Python object type that matches the
621format unit; and the entry in [square] brackets is the type of the C
622variable(s) whose address should be passed. (Use the \samp{\&}
623operator to pass a variable's address.)
624
625Note that any Python object references which are provided to the
626caller are \emph{borrowed} references; do not decrement their
627reference count!
628
629\begin{description}
630
631\item[\samp{s} (string or Unicode object) {[char *]}]
632Convert a Python string or Unicode object to a C pointer to a
633character string. You must not provide storage for the string
634itself; a pointer to an existing string is stored into the character
635pointer variable whose address you pass. The C string is
636null-terminated. The Python string must not contain embedded null
637bytes; if it does, a \exception{TypeError} exception is raised.
638Unicode objects are converted to C strings using the default
639encoding. If this conversion fails, an \exception{UnicodeError} is
640raised.
641
642\item[\samp{s\#} (string, Unicode or any read buffer compatible object)
643{[char *, int]}]
644This variant on \samp{s} stores into two C variables, the first one a
645pointer to a character string, the second one its length. In this
646case the Python string may contain embedded null bytes. Unicode
647objects pass back a pointer to the default encoded string version of the
648object if such a conversion is possible. All other read buffer
649compatible objects pass back a reference to the raw internal data
650representation.
651
652\item[\samp{z} (string or \code{None}) {[char *]}]
653Like \samp{s}, but the Python object may also be \code{None}, in which
654case the C pointer is set to \NULL{}.
655
656\item[\samp{z\#} (string or \code{None} or any read buffer compatible object)
657{[char *, int]}]
658This is to \samp{s\#} as \samp{z} is to \samp{s}.
659
660\item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
661Convert a Python Unicode object to a C pointer to a null-terminated
662buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need
663to provide storage for the Unicode data buffer; a pointer to the
664existing Unicode data is stored into the Py_UNICODE pointer variable whose
665address you pass.
666
667\item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
668This variant on \samp{u} stores into two C variables, the first one
669a pointer to a Unicode data buffer, the second one its length.
670
671\item[\samp{es} (string, Unicode object or character buffer compatible
672object) {[const char *encoding, char **buffer]}]
673This variant on \samp{s} is used for encoding Unicode and objects
674convertible to Unicode into a character buffer. It only works for
675encoded data without embedded \NULL{} bytes.
676
677The variant reads one C variable and stores into two C variables, the
678first one a pointer to an encoding name string (\var{encoding}), and the
679second a pointer to a pointer to a character buffer (\var{**buffer},
680the buffer used for storing the encoded data).
681
682The encoding name must map to a registered codec. If set to \NULL{},
683the default encoding is used.
684
685\cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
686size using \cfunction{PyMem_NEW()}, copy the encoded data into this
687buffer and adjust \var{*buffer} to reference the newly allocated
688storage. The caller is responsible for calling
689\cfunction{PyMem_Free()} to free the allocated buffer after usage.
690
691\item[\samp{et} (string, Unicode object or character buffer compatible
692object) {[const char *encoding, char **buffer]}]
693Same as \samp{es} except that string objects are passed through without
694recoding them. Instead, the implementation assumes that the string
695object uses the encoding passed in as parameter.
696
697\item[\samp{es\#} (string, Unicode object or character buffer compatible
698object) {[const char *encoding, char **buffer, int *buffer_length]}]
699This variant on \samp{s\#} is used for encoding Unicode and objects
700convertible to Unicode into a character buffer. It reads one C
701variable and stores into three C variables, the first one a pointer to
702an encoding name string (\var{encoding}), the second a pointer to a
703pointer to a character buffer (\var{**buffer}, the buffer used for
704storing the encoded data) and the third one a pointer to an integer
705(\var{*buffer_length}, the buffer length).
706
707The encoding name must map to a registered codec. If set to \NULL{},
708the default encoding is used.
709
710There are two modes of operation:
711
712If \var{*buffer} points a \NULL{} pointer,
713\cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
714size using \cfunction{PyMem_NEW()}, copy the encoded data into this
715buffer and adjust \var{*buffer} to reference the newly allocated
716storage. The caller is responsible for calling
717\cfunction{PyMem_Free()} to free the allocated buffer after usage.
718
719If \var{*buffer} points to a non-\NULL{} pointer (an already allocated
720buffer), \cfunction{PyArg_ParseTuple()} will use this location as
721buffer and interpret \var{*buffer_length} as buffer size. It will then
722copy the encoded data into the buffer and 0-terminate it. Buffer
723overflow is signalled with an exception.
724
725In both cases, \var{*buffer_length} is set to the length of the
726encoded data without the trailing 0-byte.
727
728\item[\samp{et\#} (string, Unicode object or character buffer compatible
729object) {[const char *encoding, char **buffer]}]
730Same as \samp{es\#} except that string objects are passed through without
731recoding them. Instead, the implementation assumes that the string
732object uses the encoding passed in as parameter.
733
734\item[\samp{b} (integer) {[char]}]
735Convert a Python integer to a tiny int, stored in a C \ctype{char}.
736
737\item[\samp{h} (integer) {[short int]}]
738Convert a Python integer to a C \ctype{short int}.
739
740\item[\samp{i} (integer) {[int]}]
741Convert a Python integer to a plain C \ctype{int}.
742
743\item[\samp{l} (integer) {[long int]}]
744Convert a Python integer to a C \ctype{long int}.
745
746\item[\samp{c} (string of length 1) {[char]}]
747Convert a Python character, represented as a string of length 1, to a
748C \ctype{char}.
749
750\item[\samp{f} (float) {[float]}]
751Convert a Python floating point number to a C \ctype{float}.
752
753\item[\samp{d} (float) {[double]}]
754Convert a Python floating point number to a C \ctype{double}.
755
756\item[\samp{D} (complex) {[Py_complex]}]
757Convert a Python complex number to a C \ctype{Py_complex} structure.
758
759\item[\samp{O} (object) {[PyObject *]}]
760Store a Python object (without any conversion) in a C object pointer.
761The C program thus receives the actual object that was passed. The
762object's reference count is not increased. The pointer stored is not
763\NULL{}.
764
765\item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
766Store a Python object in a C object pointer. This is similar to
767\samp{O}, but takes two C arguments: the first is the address of a
768Python type object, the second is the address of the C variable (of
769type \ctype{PyObject *}) into which the object pointer is stored.
770If the Python object does not have the required type,
771\exception{TypeError} is raised.
772
773\item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
774Convert a Python object to a C variable through a \var{converter}
775function. This takes two arguments: the first is a function, the
776second is the address of a C variable (of arbitrary type), converted
777to \ctype{void *}. The \var{converter} function in turn is called as
778follows:
779
780\var{status}\code{ = }\var{converter}\code{(}\var{object}, \var{address}\code{);}
781
782where \var{object} is the Python object to be converted and
783\var{address} is the \ctype{void *} argument that was passed to
784\cfunction{PyArg_ConvertTuple()}. The returned \var{status} should be
785\code{1} for a successful conversion and \code{0} if the conversion
786has failed. When the conversion fails, the \var{converter} function
787should raise an exception.
788
789\item[\samp{S} (string) {[PyStringObject *]}]
790Like \samp{O} but requires that the Python object is a string object.
791Raises \exception{TypeError} if the object is not a string object.
792The C variable may also be declared as \ctype{PyObject *}.
793
794\item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
795Like \samp{O} but requires that the Python object is a Unicode object.
796Raises \exception{TypeError} if the object is not a Unicode object.
797The C variable may also be declared as \ctype{PyObject *}.
798
799\item[\samp{t\#} (read-only character buffer) {[char *, int]}]
800Like \samp{s\#}, but accepts any object which implements the read-only
801buffer interface. The \ctype{char *} variable is set to point to the
802first byte of the buffer, and the \ctype{int} is set to the length of
803the buffer. Only single-segment buffer objects are accepted;
804\exception{TypeError} is raised for all others.
805
806\item[\samp{w} (read-write character buffer) {[char *]}]
807Similar to \samp{s}, but accepts any object which implements the
808read-write buffer interface. The caller must determine the length of
809the buffer by other means, or use \samp{w\#} instead. Only
810single-segment buffer objects are accepted; \exception{TypeError} is
811raised for all others.
812
813\item[\samp{w\#} (read-write character buffer) {[char *, int]}]
814Like \samp{s\#}, but accepts any object which implements the
815read-write buffer interface. The \ctype{char *} variable is set to
816point to the first byte of the buffer, and the \ctype{int} is set to
817the length of the buffer. Only single-segment buffer objects are
818accepted; \exception{TypeError} is raised for all others.
819
820\item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
821The object must be a Python sequence whose length is the number of
822format units in \var{items}. The C arguments must correspond to the
823individual format units in \var{items}. Format units for sequences
824may be nested.
825
826\strong{Note:} Prior to Python version 1.5.2, this format specifier
827only accepted a tuple containing the individual parameters, not an
828arbitrary sequence. Code which previously caused
829\exception{TypeError} to be raised here may now proceed without an
830exception. This is not expected to be a problem for existing code.
831
832\end{description}
833
834It is possible to pass Python long integers where integers are
835requested; however no proper range checking is done --- the most
836significant bits are silently truncated when the receiving field is
837too small to receive the value (actually, the semantics are inherited
838from downcasts in C --- your mileage may vary).
839
840A few other characters have a meaning in a format string. These may
841not occur inside nested parentheses. They are:
842
843\begin{description}
844
845\item[\samp{|}]
846Indicates that the remaining arguments in the Python argument list are
847optional. The C variables corresponding to optional arguments should
848be initialized to their default value --- when an optional argument is
849not specified, \cfunction{PyArg_ParseTuple()} does not touch the contents
850of the corresponding C variable(s).
851
852\item[\samp{:}]
853The list of format units ends here; the string after the colon is used
854as the function name in error messages (the ``associated value'' of
855the exception that \cfunction{PyArg_ParseTuple()} raises).
856
857\item[\samp{;}]
858The list of format units ends here; the string after the semicolon is
859used as the error message \emph{instead} of the default error message.
860Clearly, \samp{:} and \samp{;} mutually exclude each other.
861
862\end{description}
863
864Some example calls:
865
866\begin{verbatim}
867 int ok;
868 int i, j;
869 long k, l;
870 char *s;
871 int size;
872
873 ok = PyArg_ParseTuple(args, ""); /* No arguments */
874 /* Python call: f() */
875\end{verbatim}
876
877\begin{verbatim}
878 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
879 /* Possible Python call: f('whoops!') */
880\end{verbatim}
881
882\begin{verbatim}
883 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
884 /* Possible Python call: f(1, 2, 'three') */
885\end{verbatim}
886
887\begin{verbatim}
888 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
889 /* A pair of ints and a string, whose size is also returned */
890 /* Possible Python call: f((1, 2), 'three') */
891\end{verbatim}
892
893\begin{verbatim}
894 {
895 char *file;
896 char *mode = "r";
897 int bufsize = 0;
898 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
899 /* A string, and optionally another string and an integer */
900 /* Possible Python calls:
901 f('spam')
902 f('spam', 'w')
903 f('spam', 'wb', 100000) */
904 }
905\end{verbatim}
906
907\begin{verbatim}
908 {
909 int left, top, right, bottom, h, v;
910 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
911 &left, &top, &right, &bottom, &h, &v);
912 /* A rectangle and a point */
913 /* Possible Python call:
914 f(((0, 0), (400, 300)), (10, 10)) */
915 }
916\end{verbatim}
917
918\begin{verbatim}
919 {
920 Py_complex c;
921 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
922 /* a complex, also providing a function name for errors */
923 /* Possible Python call: myfunction(1+2j) */
924 }
925\end{verbatim}
926
927
928\section{Keyword Parameters for Extension Functions
929 \label{parseTupleAndKeywords}}
930
931The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
932follows:
933
934\begin{verbatim}
935int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
936 char *format, char **kwlist, ...);
937\end{verbatim}
938
939The \var{arg} and \var{format} parameters are identical to those of the
940\cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
941is the dictionary of keywords received as the third parameter from the
942Python runtime. The \var{kwlist} parameter is a \NULL{}-terminated
943list of strings which identify the parameters; the names are matched
944with the type information from \var{format} from left to right. On
945success, \cfunction{PyArg_ParseTupleAndKeywords()} returns true,
946otherwise it returns false and raises an appropriate exception.
947
948\strong{Note:} Nested tuples cannot be parsed when using keyword
949arguments! Keyword parameters passed in which are not present in the
950\var{kwlist} will cause \exception{TypeError} to be raised.
951
952Here is an example module which uses keywords, based on an example by
953Geoff Philbrick (\email{philbrick@hks.com}):%
954\index{Philbrick, Geoff}
955
956\begin{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000957#include "Python.h"
958
959static PyObject *
960keywdarg_parrot(self, args, keywds)
961 PyObject *self;
962 PyObject *args;
963 PyObject *keywds;
964{
965 int voltage;
966 char *state = "a stiff";
967 char *action = "voom";
968 char *type = "Norwegian Blue";
969
970 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
971
972 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
973 &voltage, &state, &action, &type))
974 return NULL;
975
976 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
977 action, voltage);
978 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
979
980 Py_INCREF(Py_None);
981
982 return Py_None;
983}
984
985static PyMethodDef keywdarg_methods[] = {
986 /* The cast of the function is necessary since PyCFunction values
987 * only take two PyObject* parameters, and keywdarg_parrot() takes
988 * three.
989 */
990 {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS},
991 {NULL, NULL} /* sentinel */
992};
993
994void
995initkeywdarg()
996{
997 /* Create the module and add the functions */
998 Py_InitModule("keywdarg", keywdarg_methods);
999}
1000\end{verbatim}
1001
1002
1003\section{Building Arbitrary Values
1004 \label{buildValue}}
1005
1006This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
1007declared as follows:
1008
1009\begin{verbatim}
1010PyObject *Py_BuildValue(char *format, ...);
1011\end{verbatim}
1012
1013It recognizes a set of format units similar to the ones recognized by
1014\cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
1015function, not output) must not be pointers, just values. It returns a
1016new Python object, suitable for returning from a C function called
1017from Python.
1018
1019One difference with \cfunction{PyArg_ParseTuple()}: while the latter
1020requires its first argument to be a tuple (since Python argument lists
1021are always represented as tuples internally),
1022\cfunction{Py_BuildValue()} does not always build a tuple. It builds
1023a tuple only if its format string contains two or more format units.
1024If the format string is empty, it returns \code{None}; if it contains
1025exactly one format unit, it returns whatever object is described by
1026that format unit. To force it to return a tuple of size 0 or one,
1027parenthesize the format string.
1028
1029When memory buffers are passed as parameters to supply data to build
1030objects, as for the \samp{s} and \samp{s\#} formats, the required data
1031is copied. Buffers provided by the caller are never referenced by the
1032objects created by \cfunction{Py_BuildValue()}. In other words, if
1033your code invokes \cfunction{malloc()} and passes the allocated memory
1034to \cfunction{Py_BuildValue()}, your code is responsible for
1035calling \cfunction{free()} for that memory once
1036\cfunction{Py_BuildValue()} returns.
1037
1038In the following description, the quoted form is the format unit; the
1039entry in (round) parentheses is the Python object type that the format
1040unit will return; and the entry in [square] brackets is the type of
1041the C value(s) to be passed.
1042
1043The characters space, tab, colon and comma are ignored in format
1044strings (but not within format units such as \samp{s\#}). This can be
1045used to make long format strings a tad more readable.
1046
1047\begin{description}
1048
1049\item[\samp{s} (string) {[char *]}]
1050Convert a null-terminated C string to a Python object. If the C
1051string pointer is \NULL{}, \code{None} is used.
1052
1053\item[\samp{s\#} (string) {[char *, int]}]
1054Convert a C string and its length to a Python object. If the C string
1055pointer is \NULL{}, the length is ignored and \code{None} is
1056returned.
1057
1058\item[\samp{z} (string or \code{None}) {[char *]}]
1059Same as \samp{s}.
1060
1061\item[\samp{z\#} (string or \code{None}) {[char *, int]}]
1062Same as \samp{s\#}.
1063
1064\item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1065Convert a null-terminated buffer of Unicode (UCS-2) data to a Python
1066Unicode object. If the Unicode buffer pointer is \NULL,
1067\code{None} is returned.
1068
1069\item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1070Convert a Unicode (UCS-2) data buffer and its length to a Python
1071Unicode object. If the Unicode buffer pointer is \NULL, the length
1072is ignored and \code{None} is returned.
1073
1074\item[\samp{i} (integer) {[int]}]
1075Convert a plain C \ctype{int} to a Python integer object.
1076
1077\item[\samp{b} (integer) {[char]}]
1078Same as \samp{i}.
1079
1080\item[\samp{h} (integer) {[short int]}]
1081Same as \samp{i}.
1082
1083\item[\samp{l} (integer) {[long int]}]
1084Convert a C \ctype{long int} to a Python integer object.
1085
1086\item[\samp{c} (string of length 1) {[char]}]
1087Convert a C \ctype{int} representing a character to a Python string of
1088length 1.
1089
1090\item[\samp{d} (float) {[double]}]
1091Convert a C \ctype{double} to a Python floating point number.
1092
1093\item[\samp{f} (float) {[float]}]
1094Same as \samp{d}.
1095
1096\item[\samp{D} (complex) {[Py_complex *]}]
1097Convert a C \ctype{Py_complex} structure to a Python complex number.
1098
1099\item[\samp{O} (object) {[PyObject *]}]
1100Pass a Python object untouched (except for its reference count, which
1101is incremented by one). If the object passed in is a \NULL{}
1102pointer, it is assumed that this was caused because the call producing
1103the argument found an error and set an exception. Therefore,
1104\cfunction{Py_BuildValue()} will return \NULL{} but won't raise an
1105exception. If no exception has been raised yet,
1106\cdata{PyExc_SystemError} is set.
1107
1108\item[\samp{S} (object) {[PyObject *]}]
1109Same as \samp{O}.
1110
1111\item[\samp{U} (object) {[PyObject *]}]
1112Same as \samp{O}.
1113
1114\item[\samp{N} (object) {[PyObject *]}]
1115Same as \samp{O}, except it doesn't increment the reference count on
1116the object. Useful when the object is created by a call to an object
1117constructor in the argument list.
1118
1119\item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
1120Convert \var{anything} to a Python object through a \var{converter}
1121function. The function is called with \var{anything} (which should be
1122compatible with \ctype{void *}) as its argument and should return a
1123``new'' Python object, or \NULL{} if an error occurred.
1124
1125\item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
1126Convert a sequence of C values to a Python tuple with the same number
1127of items.
1128
1129\item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
1130Convert a sequence of C values to a Python list with the same number
1131of items.
1132
1133\item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
1134Convert a sequence of C values to a Python dictionary. Each pair of
1135consecutive C values adds one item to the dictionary, serving as key
1136and value, respectively.
1137
1138\end{description}
1139
1140If there is an error in the format string, the
1141\cdata{PyExc_SystemError} exception is raised and \NULL{} returned.
1142
1143Examples (to the left the call, to the right the resulting Python value):
1144
1145\begin{verbatim}
1146 Py_BuildValue("") None
1147 Py_BuildValue("i", 123) 123
1148 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
1149 Py_BuildValue("s", "hello") 'hello'
1150 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
1151 Py_BuildValue("s#", "hello", 4) 'hell'
1152 Py_BuildValue("()") ()
1153 Py_BuildValue("(i)", 123) (123,)
1154 Py_BuildValue("(ii)", 123, 456) (123, 456)
1155 Py_BuildValue("(i,i)", 123, 456) (123, 456)
1156 Py_BuildValue("[i,i]", 123, 456) [123, 456]
1157 Py_BuildValue("{s:i,s:i}",
1158 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
1159 Py_BuildValue("((ii)(ii)) (ii)",
1160 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
1161\end{verbatim}
1162
1163
1164\section{Reference Counts
1165 \label{refcounts}}
1166
1167In languages like C or \Cpp{}, the programmer is responsible for
1168dynamic allocation and deallocation of memory on the heap. In C,
1169this is done using the functions \cfunction{malloc()} and
1170\cfunction{free()}. In \Cpp{}, the operators \keyword{new} and
1171\keyword{delete} are used with essentially the same meaning; they are
1172actually implemented using \cfunction{malloc()} and
1173\cfunction{free()}, so we'll restrict the following discussion to the
1174latter.
1175
1176Every block of memory allocated with \cfunction{malloc()} should
1177eventually be returned to the pool of available memory by exactly one
1178call to \cfunction{free()}. It is important to call
1179\cfunction{free()} at the right time. If a block's address is
1180forgotten but \cfunction{free()} is not called for it, the memory it
1181occupies cannot be reused until the program terminates. This is
1182called a \dfn{memory leak}. On the other hand, if a program calls
1183\cfunction{free()} for a block and then continues to use the block, it
1184creates a conflict with re-use of the block through another
1185\cfunction{malloc()} call. This is called \dfn{using freed memory}.
1186It has the same bad consequences as referencing uninitialized data ---
1187core dumps, wrong results, mysterious crashes.
1188
1189Common causes of memory leaks are unusual paths through the code. For
1190instance, a function may allocate a block of memory, do some
1191calculation, and then free the block again. Now a change in the
1192requirements for the function may add a test to the calculation that
1193detects an error condition and can return prematurely from the
1194function. It's easy to forget to free the allocated memory block when
1195taking this premature exit, especially when it is added later to the
1196code. Such leaks, once introduced, often go undetected for a long
1197time: the error exit is taken only in a small fraction of all calls,
1198and most modern machines have plenty of virtual memory, so the leak
1199only becomes apparent in a long-running process that uses the leaking
1200function frequently. Therefore, it's important to prevent leaks from
1201happening by having a coding convention or strategy that minimizes
1202this kind of errors.
1203
1204Since Python makes heavy use of \cfunction{malloc()} and
1205\cfunction{free()}, it needs a strategy to avoid memory leaks as well
1206as the use of freed memory. The chosen method is called
1207\dfn{reference counting}. The principle is simple: every object
1208contains a counter, which is incremented when a reference to the
1209object is stored somewhere, and which is decremented when a reference
1210to it is deleted. When the counter reaches zero, the last reference
1211to the object has been deleted and the object is freed.
1212
1213An alternative strategy is called \dfn{automatic garbage collection}.
1214(Sometimes, reference counting is also referred to as a garbage
1215collection strategy, hence my use of ``automatic'' to distinguish the
1216two.) The big advantage of automatic garbage collection is that the
1217user doesn't need to call \cfunction{free()} explicitly. (Another claimed
1218advantage is an improvement in speed or memory usage --- this is no
1219hard fact however.) The disadvantage is that for C, there is no
1220truly portable automatic garbage collector, while reference counting
1221can be implemented portably (as long as the functions \cfunction{malloc()}
1222and \cfunction{free()} are available --- which the C Standard guarantees).
1223Maybe some day a sufficiently portable automatic garbage collector
1224will be available for C. Until then, we'll have to live with
1225reference counts.
1226
1227\subsection{Reference Counting in Python
1228 \label{refcountsInPython}}
1229
1230There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
1231which handle the incrementing and decrementing of the reference count.
1232\cfunction{Py_DECREF()} also frees the object when the count reaches zero.
1233For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
1234makes a call through a function pointer in the object's \dfn{type
1235object}. For this purpose (and others), every object also contains a
1236pointer to its type object.
1237
1238The big question now remains: when to use \code{Py_INCREF(x)} and
1239\code{Py_DECREF(x)}? Let's first introduce some terms. Nobody
1240``owns'' an object; however, you can \dfn{own a reference} to an
1241object. An object's reference count is now defined as the number of
1242owned references to it. The owner of a reference is responsible for
1243calling \cfunction{Py_DECREF()} when the reference is no longer
1244needed. Ownership of a reference can be transferred. There are three
1245ways to dispose of an owned reference: pass it on, store it, or call
1246\cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
1247creates a memory leak.
1248
1249It is also possible to \dfn{borrow}\footnote{The metaphor of
1250``borrowing'' a reference is not completely correct: the owner still
1251has a copy of the reference.} a reference to an object. The borrower
1252of a reference should not call \cfunction{Py_DECREF()}. The borrower must
1253not hold on to the object longer than the owner from which it was
1254borrowed. Using a borrowed reference after the owner has disposed of
1255it risks using freed memory and should be avoided
1256completely.\footnote{Checking that the reference count is at least 1
1257\strong{does not work} --- the reference count itself could be in
1258freed memory and may thus be reused for another object!}
1259
1260The advantage of borrowing over owning a reference is that you don't
1261need to take care of disposing of the reference on all possible paths
1262through the code --- in other words, with a borrowed reference you
1263don't run the risk of leaking when a premature exit is taken. The
1264disadvantage of borrowing over leaking is that there are some subtle
1265situations where in seemingly correct code a borrowed reference can be
1266used after the owner from which it was borrowed has in fact disposed
1267of it.
1268
1269A borrowed reference can be changed into an owned reference by calling
1270\cfunction{Py_INCREF()}. This does not affect the status of the owner from
1271which the reference was borrowed --- it creates a new owned reference,
1272and gives full owner responsibilities (the new owner must
1273dispose of the reference properly, as well as the previous owner).
1274
1275
1276\subsection{Ownership Rules
1277 \label{ownershipRules}}
1278
1279Whenever an object reference is passed into or out of a function, it
1280is part of the function's interface specification whether ownership is
1281transferred with the reference or not.
1282
1283Most functions that return a reference to an object pass on ownership
1284with the reference. In particular, all functions whose function it is
1285to create a new object, such as \cfunction{PyInt_FromLong()} and
1286\cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if in
1287fact, in some cases, you don't receive a reference to a brand new
1288object, you still receive ownership of the reference. For instance,
1289\cfunction{PyInt_FromLong()} maintains a cache of popular values and can
1290return a reference to a cached item.
1291
1292Many functions that extract objects from other objects also transfer
1293ownership with the reference, for instance
1294\cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
1295however, since a few common routines are exceptions:
1296\cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
1297\cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
1298all return references that you borrow from the tuple, list or
1299dictionary.
1300
1301The function \cfunction{PyImport_AddModule()} also returns a borrowed
1302reference, even though it may actually create the object it returns:
1303this is possible because an owned reference to the object is stored in
1304\code{sys.modules}.
1305
1306When you pass an object reference into another function, in general,
1307the function borrows the reference from you --- if it needs to store
1308it, it will use \cfunction{Py_INCREF()} to become an independent
1309owner. There are exactly two important exceptions to this rule:
1310\cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
1311functions take over ownership of the item passed to them --- even if
1312they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
1313take over ownership --- they are ``normal.'')
1314
1315When a C function is called from Python, it borrows references to its
1316arguments from the caller. The caller owns a reference to the object,
1317so the borrowed reference's lifetime is guaranteed until the function
1318returns. Only when such a borrowed reference must be stored or passed
1319on, it must be turned into an owned reference by calling
1320\cfunction{Py_INCREF()}.
1321
1322The object reference returned from a C function that is called from
1323Python must be an owned reference --- ownership is tranferred from the
1324function to its caller.
1325
1326
1327\subsection{Thin Ice
1328 \label{thinIce}}
1329
1330There are a few situations where seemingly harmless use of a borrowed
1331reference can lead to problems. These all have to do with implicit
1332invocations of the interpreter, which can cause the owner of a
1333reference to dispose of it.
1334
1335The first and most important case to know about is using
1336\cfunction{Py_DECREF()} on an unrelated object while borrowing a
1337reference to a list item. For instance:
1338
1339\begin{verbatim}
1340bug(PyObject *list) {
1341 PyObject *item = PyList_GetItem(list, 0);
1342
1343 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1344 PyObject_Print(item, stdout, 0); /* BUG! */
1345}
1346\end{verbatim}
1347
1348This function first borrows a reference to \code{list[0]}, then
1349replaces \code{list[1]} with the value \code{0}, and finally prints
1350the borrowed reference. Looks harmless, right? But it's not!
1351
1352Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
1353owns references to all its items, so when item 1 is replaced, it has
1354to dispose of the original item 1. Now let's suppose the original
1355item 1 was an instance of a user-defined class, and let's further
1356suppose that the class defined a \method{__del__()} method. If this
1357class instance has a reference count of 1, disposing of it will call
1358its \method{__del__()} method.
1359
1360Since it is written in Python, the \method{__del__()} method can execute
1361arbitrary Python code. Could it perhaps do something to invalidate
1362the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
1363that the list passed into \cfunction{bug()} is accessible to the
1364\method{__del__()} method, it could execute a statement to the effect of
1365\samp{del list[0]}, and assuming this was the last reference to that
1366object, it would free the memory associated with it, thereby
1367invalidating \code{item}.
1368
1369The solution, once you know the source of the problem, is easy:
1370temporarily increment the reference count. The correct version of the
1371function reads:
1372
1373\begin{verbatim}
1374no_bug(PyObject *list) {
1375 PyObject *item = PyList_GetItem(list, 0);
1376
1377 Py_INCREF(item);
1378 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1379 PyObject_Print(item, stdout, 0);
1380 Py_DECREF(item);
1381}
1382\end{verbatim}
1383
1384This is a true story. An older version of Python contained variants
1385of this bug and someone spent a considerable amount of time in a C
1386debugger to figure out why his \method{__del__()} methods would fail...
1387
1388The second case of problems with a borrowed reference is a variant
1389involving threads. Normally, multiple threads in the Python
1390interpreter can't get in each other's way, because there is a global
1391lock protecting Python's entire object space. However, it is possible
1392to temporarily release this lock using the macro
1393\code{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
1394\code{Py_END_ALLOW_THREADS}. This is common around blocking I/O
1395calls, to let other threads use the processor while waiting for the I/O to
1396complete. Obviously, the following function has the same problem as
1397the previous one:
1398
1399\begin{verbatim}
1400bug(PyObject *list) {
1401 PyObject *item = PyList_GetItem(list, 0);
1402 Py_BEGIN_ALLOW_THREADS
1403 ...some blocking I/O call...
1404 Py_END_ALLOW_THREADS
1405 PyObject_Print(item, stdout, 0); /* BUG! */
1406}
1407\end{verbatim}
1408
1409
1410\subsection{NULL Pointers
1411 \label{nullPointers}}
1412
1413In general, functions that take object references as arguments do not
1414expect you to pass them \NULL{} pointers, and will dump core (or
1415cause later core dumps) if you do so. Functions that return object
1416references generally return \NULL{} only to indicate that an
1417exception occurred. The reason for not testing for \NULL{}
1418arguments is that functions often pass the objects they receive on to
1419other function --- if each function were to test for \NULL{},
1420there would be a lot of redundant tests and the code would run more
1421slowly.
1422
1423It is better to test for \NULL{} only at the ``source:'' when a
1424pointer that may be \NULL{} is received, for example, from
1425\cfunction{malloc()} or from a function that may raise an exception.
1426
1427The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
1428do not check for \NULL{} pointers --- however, their variants
1429\cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
1430
1431The macros for checking for a particular object type
1432(\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
1433again, there is much code that calls several of these in a row to test
1434an object against various different expected types, and this would
1435generate redundant tests. There are no variants with \NULL{}
1436checking.
1437
1438The C function calling mechanism guarantees that the argument list
1439passed to C functions (\code{args} in the examples) is never
1440\NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
1441These guarantees don't hold when you use the ``old'' style
1442calling convention --- this is still found in much existing code.}
1443
1444It is a severe error to ever let a \NULL{} pointer ``escape'' to
1445the Python user.
1446
1447% Frank Stajano:
1448% A pedagogically buggy example, along the lines of the previous listing,
1449% would be helpful here -- showing in more concrete terms what sort of
1450% actions could cause the problem. I can't very well imagine it from the
1451% description.
1452
1453
1454\section{Writing Extensions in \Cpp{}
1455 \label{cplusplus}}
1456
1457It is possible to write extension modules in \Cpp{}. Some restrictions
1458apply. If the main program (the Python interpreter) is compiled and
1459linked by the C compiler, global or static objects with constructors
1460cannot be used. This is not a problem if the main program is linked
1461by the \Cpp{} compiler. Functions that will be called by the
1462Python interpreter (in particular, module initalization functions)
1463have to be declared using \code{extern "C"}.
1464It is unnecessary to enclose the Python header files in
1465\code{extern "C" \{...\}} --- they use this form already if the symbol
1466\samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
1467symbol).
1468
1469
1470\section{Providing a C API for an Extension Module
1471 \label{using-cobjects}}
1472\sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
1473
1474Many extension modules just provide new functions and types to be
1475used from Python, but sometimes the code in an extension module can
1476be useful for other extension modules. For example, an extension
1477module could implement a type ``collection'' which works like lists
1478without order. Just like the standard Python list type has a C API
1479which permits extension modules to create and manipulate lists, this
1480new collection type should have a set of C functions for direct
1481manipulation from other extension modules.
1482
1483At first sight this seems easy: just write the functions (without
1484declaring them \keyword{static}, of course), provide an appropriate
1485header file, and document the C API. And in fact this would work if
1486all extension modules were always linked statically with the Python
1487interpreter. When modules are used as shared libraries, however, the
1488symbols defined in one module may not be visible to another module.
1489The details of visibility depend on the operating system; some systems
1490use one global namespace for the Python interpreter and all extension
1491modules (Windows, for example), whereas others require an explicit
1492list of imported symbols at module link time (AIX is one example), or
1493offer a choice of different strategies (most Unices). And even if
1494symbols are globally visible, the module whose functions one wishes to
1495call might not have been loaded yet!
1496
1497Portability therefore requires not to make any assumptions about
1498symbol visibility. This means that all symbols in extension modules
1499should be declared \keyword{static}, except for the module's
1500initialization function, in order to avoid name clashes with other
1501extension modules (as discussed in section~\ref{methodTable}). And it
1502means that symbols that \emph{should} be accessible from other
1503extension modules must be exported in a different way.
1504
1505Python provides a special mechanism to pass C-level information
1506(pointers) from one extension module to another one: CObjects.
1507A CObject is a Python data type which stores a pointer (\ctype{void
1508*}). CObjects can only be created and accessed via their C API, but
1509they can be passed around like any other Python object. In particular,
1510they can be assigned to a name in an extension module's namespace.
1511Other extension modules can then import this module, retrieve the
1512value of this name, and then retrieve the pointer from the CObject.
1513
1514There are many ways in which CObjects can be used to export the C API
1515of an extension module. Each name could get its own CObject, or all C
1516API pointers could be stored in an array whose address is published in
1517a CObject. And the various tasks of storing and retrieving the pointers
1518can be distributed in different ways between the module providing the
1519code and the client modules.
1520
1521The following example demonstrates an approach that puts most of the
1522burden on the writer of the exporting module, which is appropriate
1523for commonly used library modules. It stores all C API pointers
1524(just one in the example!) in an array of \ctype{void} pointers which
1525becomes the value of a CObject. The header file corresponding to
1526the module provides a macro that takes care of importing the module
1527and retrieving its C API pointers; client modules only have to call
1528this macro before accessing the C API.
1529
1530The exporting module is a modification of the \module{spam} module from
1531section~\ref{simpleExample}. The function \function{spam.system()}
1532does not call the C library function \cfunction{system()} directly,
1533but a function \cfunction{PySpam_System()}, which would of course do
1534something more complicated in reality (such as adding ``spam'' to
1535every command). This function \cfunction{PySpam_System()} is also
1536exported to other extension modules.
1537
1538The function \cfunction{PySpam_System()} is a plain C function,
1539declared \keyword{static} like everything else:
1540
1541\begin{verbatim}
1542static int
1543PySpam_System(command)
1544 char *command;
1545{
1546 return system(command);
1547}
1548\end{verbatim}
1549
1550The function \cfunction{spam_system()} is modified in a trivial way:
1551
1552\begin{verbatim}
1553static PyObject *
1554spam_system(self, args)
1555 PyObject *self;
1556 PyObject *args;
1557{
1558 char *command;
1559 int sts;
1560
1561 if (!PyArg_ParseTuple(args, "s", &command))
1562 return NULL;
1563 sts = PySpam_System(command);
1564 return Py_BuildValue("i", sts);
1565}
1566\end{verbatim}
1567
1568In the beginning of the module, right after the line
1569
1570\begin{verbatim}
1571#include "Python.h"
1572\end{verbatim}
1573
1574two more lines must be added:
1575
1576\begin{verbatim}
1577#define SPAM_MODULE
1578#include "spammodule.h"
1579\end{verbatim}
1580
1581The \code{\#define} is used to tell the header file that it is being
1582included in the exporting module, not a client module. Finally,
1583the module's initialization function must take care of initializing
1584the C API pointer array:
1585
1586\begin{verbatim}
1587void
1588initspam()
1589{
1590 PyObject *m;
1591 static void *PySpam_API[PySpam_API_pointers];
1592 PyObject *c_api_object;
1593
1594 m = Py_InitModule("spam", SpamMethods);
1595
1596 /* Initialize the C API pointer array */
1597 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1598
1599 /* Create a CObject containing the API pointer array's address */
1600 c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
1601
1602 if (c_api_object != NULL) {
1603 /* Create a name for this object in the module's namespace */
1604 PyObject *d = PyModule_GetDict(m);
1605
1606 PyDict_SetItemString(d, "_C_API", c_api_object);
1607 Py_DECREF(c_api_object);
1608 }
1609}
1610\end{verbatim}
1611
1612Note that \code{PySpam_API} is declared \code{static}; otherwise
1613the pointer array would disappear when \code{initspam} terminates!
1614
1615The bulk of the work is in the header file \file{spammodule.h},
1616which looks like this:
1617
1618\begin{verbatim}
1619#ifndef Py_SPAMMODULE_H
1620#define Py_SPAMMODULE_H
1621#ifdef __cplusplus
1622extern "C" {
1623#endif
1624
1625/* Header file for spammodule */
1626
1627/* C API functions */
1628#define PySpam_System_NUM 0
1629#define PySpam_System_RETURN int
1630#define PySpam_System_PROTO (char *command)
1631
1632/* Total number of C API pointers */
1633#define PySpam_API_pointers 1
1634
1635
1636#ifdef SPAM_MODULE
1637/* This section is used when compiling spammodule.c */
1638
1639static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1640
1641#else
1642/* This section is used in modules that use spammodule's API */
1643
1644static void **PySpam_API;
1645
1646#define PySpam_System \
1647 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1648
1649#define import_spam() \
1650{ \
1651 PyObject *module = PyImport_ImportModule("spam"); \
1652 if (module != NULL) { \
1653 PyObject *module_dict = PyModule_GetDict(module); \
1654 PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
1655 if (PyCObject_Check(c_api_object)) { \
1656 PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
1657 } \
1658 } \
1659}
1660
1661#endif
1662
1663#ifdef __cplusplus
1664}
1665#endif
1666
1667#endif /* !defined(Py_SPAMMODULE_H */
1668\end{verbatim}
1669
1670All that a client module must do in order to have access to the
1671function \cfunction{PySpam_System()} is to call the function (or
1672rather macro) \cfunction{import_spam()} in its initialization
1673function:
1674
1675\begin{verbatim}
1676void
1677initclient()
1678{
1679 PyObject *m;
1680
1681 Py_InitModule("client", ClientMethods);
1682 import_spam();
1683}
1684\end{verbatim}
1685
1686The main disadvantage of this approach is that the file
1687\file{spammodule.h} is rather complicated. However, the
1688basic structure is the same for each function that is
1689exported, so it has to be learned only once.
1690
1691Finally it should be mentioned that CObjects offer additional
1692functionality, which is especially useful for memory allocation and
1693deallocation of the pointer stored in a CObject. The details
1694are described in the \citetitle[../api/api.html]{Python/C API
1695Reference Manual} in the section ``CObjects'' and in the
1696implementation of CObjects (files \file{Include/cobject.h} and
1697\file{Objects/cobject.c} in the Python source code distribution).