blob: 9b6517a6d900f70a721a582e16fb9f3fe928ffe9 [file] [log] [blame]
Fred Drakec37b65e2001-11-28 07:26:15 +00001\chapter{Extending Python with C or \Cpp \label{intro}}
Fred Drakecc8f44b2001-08-20 19:30:29 +00002
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
Fred Drakeef6373a2001-11-17 06:50:42 +0000218initspam(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +0000219{
Fred Drake63e40a52002-04-12 19:08:31 +0000220 PyObject *m;
Fred Drakecc8f44b2001-08-20 19:30:29 +0000221
222 m = Py_InitModule("spam", SpamMethods);
Fred Drake63e40a52002-04-12 19:08:31 +0000223
Fred Drakecc8f44b2001-08-20 19:30:29 +0000224 SpamError = PyErr_NewException("spam.error", NULL, NULL);
Fred Drake63e40a52002-04-12 19:08:31 +0000225 Py_INCREF(SpamError);
226 PyModule_AddObject(m, "error", SpamError);
Fred Drakecc8f44b2001-08-20 19:30:29 +0000227}
228\end{verbatim}
229
230Note that the Python name for the exception object is
231\exception{spam.error}. The \cfunction{PyErr_NewException()} function
232may create a class with the base class being \exception{Exception}
233(unless another class is passed in instead of \NULL), described in the
234\citetitle[../lib/lib.html]{Python Library Reference} under ``Built-in
235Exceptions.''
236
237Note also that the \cdata{SpamError} variable retains a reference to
238the newly created exception class; this is intentional! Since the
239exception could be removed from the module by external code, an owned
240reference to the class is needed to ensure that it will not be
241discarded, causing \cdata{SpamError} to become a dangling pointer.
242Should it become a dangling pointer, C code which raises the exception
243could cause a core dump or other unintended side effects.
244
245
246\section{Back to the Example
247 \label{backToExample}}
248
249Going back to our example function, you should now be able to
250understand this statement:
251
252\begin{verbatim}
253 if (!PyArg_ParseTuple(args, "s", &command))
254 return NULL;
255\end{verbatim}
256
257It returns \NULL{} (the error indicator for functions returning
258object pointers) if an error is detected in the argument list, relying
259on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the
260string value of the argument has been copied to the local variable
261\cdata{command}. This is a pointer assignment and you are not supposed
262to modify the string to which it points (so in Standard C, the variable
263\cdata{command} should properly be declared as \samp{const char
264*command}).
265
266The next statement is a call to the \UNIX{} function
267\cfunction{system()}, passing it the string we just got from
268\cfunction{PyArg_ParseTuple()}:
269
270\begin{verbatim}
271 sts = system(command);
272\end{verbatim}
273
274Our \function{spam.system()} function must return the value of
275\cdata{sts} as a Python object. This is done using the function
276\cfunction{Py_BuildValue()}, which is something like the inverse of
277\cfunction{PyArg_ParseTuple()}: it takes a format string and an
278arbitrary number of C values, and returns a new Python object.
279More info on \cfunction{Py_BuildValue()} is given later.
280
281\begin{verbatim}
282 return Py_BuildValue("i", sts);
283\end{verbatim}
284
285In this case, it will return an integer object. (Yes, even integers
286are objects on the heap in Python!)
287
288If you have a C function that returns no useful argument (a function
289returning \ctype{void}), the corresponding Python function must return
290\code{None}. You need this idiom to do so:
291
292\begin{verbatim}
293 Py_INCREF(Py_None);
294 return Py_None;
295\end{verbatim}
296
297\cdata{Py_None} is the C name for the special Python object
298\code{None}. It is a genuine Python object rather than a \NULL{}
299pointer, which means ``error'' in most contexts, as we have seen.
300
301
302\section{The Module's Method Table and Initialization Function
303 \label{methodTable}}
304
305I promised to show how \cfunction{spam_system()} is called from Python
306programs. First, we need to list its name and address in a ``method
307table'':
308
309\begin{verbatim}
310static PyMethodDef SpamMethods[] = {
311 ...
Fred Drakeef6373a2001-11-17 06:50:42 +0000312 {"system", spam_system, METH_VARARGS,
313 "Execute a shell command."},
Fred Drakecc8f44b2001-08-20 19:30:29 +0000314 ...
Fred Drakeef6373a2001-11-17 06:50:42 +0000315 {NULL, NULL, 0, NULL} /* Sentinel */
Fred Drakecc8f44b2001-08-20 19:30:29 +0000316};
317\end{verbatim}
318
319Note the third entry (\samp{METH_VARARGS}). This is a flag telling
320the interpreter the calling convention to be used for the C
321function. It should normally always be \samp{METH_VARARGS} or
322\samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an
323obsolete variant of \cfunction{PyArg_ParseTuple()} is used.
324
325When using only \samp{METH_VARARGS}, the function should expect
326the Python-level parameters to be passed in as a tuple acceptable for
327parsing via \cfunction{PyArg_ParseTuple()}; more information on this
328function is provided below.
329
330The \constant{METH_KEYWORDS} bit may be set in the third field if
331keyword arguments should be passed to the function. In this case, the
332C function should accept a third \samp{PyObject *} parameter which
333will be a dictionary of keywords. Use
334\cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to
335such a function.
336
337The method table must be passed to the interpreter in the module's
338initialization function. The initialization function must be named
339\cfunction{init\var{name}()}, where \var{name} is the name of the
340module, and should be the only non-\keyword{static} item defined in
341the module file:
342
343\begin{verbatim}
344void
Fred Drakeef6373a2001-11-17 06:50:42 +0000345initspam(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +0000346{
347 (void) Py_InitModule("spam", SpamMethods);
348}
349\end{verbatim}
350
351Note that for \Cpp, this method must be declared \code{extern "C"}.
352
353When the Python program imports module \module{spam} for the first
354time, \cfunction{initspam()} is called. (See below for comments about
355embedding Python.) It calls
356\cfunction{Py_InitModule()}, which creates a ``module object'' (which
357is inserted in the dictionary \code{sys.modules} under the key
358\code{"spam"}), and inserts built-in function objects into the newly
359created module based upon the table (an array of \ctype{PyMethodDef}
360structures) that was passed as its second argument.
361\cfunction{Py_InitModule()} returns a pointer to the module object
362that it creates (which is unused here). It aborts with a fatal error
363if the module could not be initialized satisfactorily, so the caller
364doesn't need to check for errors.
365
366When embedding Python, the \cfunction{initspam()} function is not
367called automatically unless there's an entry in the
368\cdata{_PyImport_Inittab} table. The easiest way to handle this is to
369statically initialize your statically-linked modules by directly
370calling \cfunction{initspam()} after the call to
371\cfunction{Py_Initialize()} or \cfunction{PyMac_Initialize()}:
372
373\begin{verbatim}
374int main(int argc, char **argv)
375{
376 /* Pass argv[0] to the Python interpreter */
377 Py_SetProgramName(argv[0]);
378
379 /* Initialize the Python interpreter. Required. */
380 Py_Initialize();
381
382 /* Add a static module */
383 initspam();
384\end{verbatim}
385
386An example may be found in the file \file{Demo/embed/demo.c} in the
387Python source distribution.
388
Fred Drake0aa811c2001-10-20 04:24:09 +0000389\note{Removing entries from \code{sys.modules} or importing
Fred Drakecc8f44b2001-08-20 19:30:29 +0000390compiled modules into multiple interpreters within a process (or
391following a \cfunction{fork()} without an intervening
392\cfunction{exec()}) can create problems for some extension modules.
393Extension module authors should exercise caution when initializing
394internal data structures.
395Note also that the \function{reload()} function can be used with
396extension modules, and will call the module initialization function
397(\cfunction{initspam()} in the example), but will not load the module
398again if it was loaded from a dynamically loadable object file
Fred Drake0aa811c2001-10-20 04:24:09 +0000399(\file{.so} on \UNIX, \file{.dll} on Windows).}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000400
401A more substantial example module is included in the Python source
402distribution as \file{Modules/xxmodule.c}. This file may be used as a
403template or simply read as an example. The \program{modulator.py}
404script included in the source distribution or Windows install provides
405a simple graphical user interface for declaring the functions and
406objects which a module should implement, and can generate a template
407which can be filled in. The script lives in the
408\file{Tools/modulator/} directory; see the \file{README} file there
409for more information.
410
411
412\section{Compilation and Linkage
413 \label{compilation}}
414
415There are two more things to do before you can use your new extension:
416compiling and linking it with the Python system. If you use dynamic
Fred Drake4e765552002-05-16 13:48:14 +0000417loading, the details may depend on the style of dynamic loading your
418system uses; see the chapters about building extension modules
419(chapter \ref{building}) and additional information that pertains only
420to building on Windows (chapter \ref{building-on-windows}) for more
421information about this.
422% XXX Add information about Mac OS
Fred Drakecc8f44b2001-08-20 19:30:29 +0000423
424If you can't use dynamic loading, or if you want to make your module a
425permanent part of the Python interpreter, you will have to change the
426configuration setup and rebuild the interpreter. Luckily, this is
Fred Drake4e765552002-05-16 13:48:14 +0000427very simple on \UNIX: just place your file (\file{spammodule.c} for
428example) in the \file{Modules/} directory of an unpacked source
429distribution, add a line to the file \file{Modules/Setup.local}
430describing your file:
Fred Drakecc8f44b2001-08-20 19:30:29 +0000431
432\begin{verbatim}
433spam spammodule.o
434\end{verbatim}
435
436and rebuild the interpreter by running \program{make} in the toplevel
437directory. You can also run \program{make} in the \file{Modules/}
438subdirectory, but then you must first rebuild \file{Makefile}
439there by running `\program{make} Makefile'. (This is necessary each
440time you change the \file{Setup} file.)
441
442If your module requires additional libraries to link with, these can
443be listed on the line in the configuration file as well, for instance:
444
445\begin{verbatim}
446spam spammodule.o -lX11
447\end{verbatim}
448
449\section{Calling Python Functions from C
450 \label{callingPython}}
451
452So far we have concentrated on making C functions callable from
453Python. The reverse is also useful: calling Python functions from C.
454This is especially the case for libraries that support so-called
455``callback'' functions. If a C interface makes use of callbacks, the
456equivalent Python often needs to provide a callback mechanism to the
457Python programmer; the implementation will require calling the Python
458callback functions from a C callback. Other uses are also imaginable.
459
460Fortunately, the Python interpreter is easily called recursively, and
461there is a standard interface to call a Python function. (I won't
462dwell on how to call the Python parser with a particular string as
463input --- if you're interested, have a look at the implementation of
464the \programopt{-c} command line option in \file{Python/pythonmain.c}
465from the Python source code.)
466
467Calling a Python function is easy. First, the Python program must
468somehow pass you the Python function object. You should provide a
469function (or some other interface) to do this. When this function is
470called, save a pointer to the Python function object (be careful to
471\cfunction{Py_INCREF()} it!) in a global variable --- or wherever you
472see fit. For example, the following function might be part of a module
473definition:
474
475\begin{verbatim}
476static PyObject *my_callback = NULL;
477
478static PyObject *
479my_set_callback(dummy, args)
480 PyObject *dummy, *args;
481{
482 PyObject *result = NULL;
483 PyObject *temp;
484
485 if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
486 if (!PyCallable_Check(temp)) {
487 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
488 return NULL;
489 }
490 Py_XINCREF(temp); /* Add a reference to new callback */
491 Py_XDECREF(my_callback); /* Dispose of previous callback */
492 my_callback = temp; /* Remember new callback */
493 /* Boilerplate to return "None" */
494 Py_INCREF(Py_None);
495 result = Py_None;
496 }
497 return result;
498}
499\end{verbatim}
500
501This function must be registered with the interpreter using the
502\constant{METH_VARARGS} flag; this is described in section
503\ref{methodTable}, ``The Module's Method Table and Initialization
504Function.'' The \cfunction{PyArg_ParseTuple()} function and its
Fred Drakec37b65e2001-11-28 07:26:15 +0000505arguments are documented in section~\ref{parseTuple}, ``Extracting
Fred Drakecc8f44b2001-08-20 19:30:29 +0000506Parameters in Extension Functions.''
507
508The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()}
509increment/decrement the reference count of an object and are safe in
510the presence of \NULL{} pointers (but note that \var{temp} will not be
Fred Drakec37b65e2001-11-28 07:26:15 +0000511\NULL{} in this context). More info on them in
512section~\ref{refcounts}, ``Reference Counts.''
Fred Drakecc8f44b2001-08-20 19:30:29 +0000513
514Later, when it is time to call the function, you call the C function
Fred Drake99181ac2001-11-29 05:02:34 +0000515\cfunction{PyEval_CallObject()}.\ttindex{PyEval_CallObject()} This
516function has two arguments, both pointers to arbitrary Python objects:
517the Python function, and the argument list. The argument list must
518always be a tuple object, whose length is the number of arguments. To
519call the Python function with no arguments, pass an empty tuple; to
520call it with one argument, pass a singleton tuple.
521\cfunction{Py_BuildValue()} returns a tuple when its format string
522consists of zero or more format codes between parentheses. For
523example:
Fred Drakecc8f44b2001-08-20 19:30:29 +0000524
525\begin{verbatim}
526 int arg;
527 PyObject *arglist;
528 PyObject *result;
529 ...
530 arg = 123;
531 ...
532 /* Time to call the callback */
533 arglist = Py_BuildValue("(i)", arg);
534 result = PyEval_CallObject(my_callback, arglist);
535 Py_DECREF(arglist);
536\end{verbatim}
537
538\cfunction{PyEval_CallObject()} returns a Python object pointer: this is
539the return value of the Python function. \cfunction{PyEval_CallObject()} is
540``reference-count-neutral'' with respect to its arguments. In the
541example a new tuple was created to serve as the argument list, which
542is \cfunction{Py_DECREF()}-ed immediately after the call.
543
544The return value of \cfunction{PyEval_CallObject()} is ``new'': either it
545is a brand new object, or it is an existing object whose reference
546count has been incremented. So, unless you want to save it in a
547global variable, you should somehow \cfunction{Py_DECREF()} the result,
548even (especially!) if you are not interested in its value.
549
550Before you do this, however, it is important to check that the return
Fred Drakec37b65e2001-11-28 07:26:15 +0000551value isn't \NULL. If it is, the Python function terminated by
Fred Drakecc8f44b2001-08-20 19:30:29 +0000552raising an exception. If the C code that called
553\cfunction{PyEval_CallObject()} is called from Python, it should now
554return an error indication to its Python caller, so the interpreter
555can print a stack trace, or the calling Python code can handle the
556exception. If this is not possible or desirable, the exception should
557be cleared by calling \cfunction{PyErr_Clear()}. For example:
558
559\begin{verbatim}
560 if (result == NULL)
561 return NULL; /* Pass error back */
562 ...use result...
563 Py_DECREF(result);
564\end{verbatim}
565
566Depending on the desired interface to the Python callback function,
567you may also have to provide an argument list to
568\cfunction{PyEval_CallObject()}. In some cases the argument list is
569also provided by the Python program, through the same interface that
570specified the callback function. It can then be saved and used in the
571same manner as the function object. In other cases, you may have to
572construct a new tuple to pass as the argument list. The simplest way
573to do this is to call \cfunction{Py_BuildValue()}. For example, if
574you want to pass an integral event code, you might use the following
575code:
576
577\begin{verbatim}
578 PyObject *arglist;
579 ...
580 arglist = Py_BuildValue("(l)", eventcode);
581 result = PyEval_CallObject(my_callback, arglist);
582 Py_DECREF(arglist);
583 if (result == NULL)
584 return NULL; /* Pass error back */
585 /* Here maybe use the result */
586 Py_DECREF(result);
587\end{verbatim}
588
589Note the placement of \samp{Py_DECREF(arglist)} immediately after the
590call, before the error check! Also note that strictly spoken this
591code is not complete: \cfunction{Py_BuildValue()} may run out of
592memory, and this should be checked.
593
594
595\section{Extracting Parameters in Extension Functions
596 \label{parseTuple}}
597
Fred Drakee9fba912002-03-28 22:36:56 +0000598\ttindex{PyArg_ParseTuple()}
599
Fred Drakecc8f44b2001-08-20 19:30:29 +0000600The \cfunction{PyArg_ParseTuple()} function is declared as follows:
601
602\begin{verbatim}
603int PyArg_ParseTuple(PyObject *arg, char *format, ...);
604\end{verbatim}
605
606The \var{arg} argument must be a tuple object containing an argument
607list passed from Python to a C function. The \var{format} argument
Fred Drake68304cc2002-04-05 23:01:14 +0000608must be a format string, whose syntax is explained in
609``\ulink{Parsing arguments and building
610values}{../api/arg-parsing.html}'' in the
611\citetitle[../api/api.html]{Python/C API Reference Manual}. The
Fred Drakecc8f44b2001-08-20 19:30:29 +0000612remaining arguments must be addresses of variables whose type is
Fred Drake68304cc2002-04-05 23:01:14 +0000613determined by the format string.
Fred Drakecc8f44b2001-08-20 19:30:29 +0000614
615Note that while \cfunction{PyArg_ParseTuple()} checks that the Python
616arguments have the required types, it cannot check the validity of the
617addresses of C variables passed to the call: if you make mistakes
618there, your code will probably crash or at least overwrite random bits
619in memory. So be careful!
620
Fred Drakecc8f44b2001-08-20 19:30:29 +0000621Note that any Python object references which are provided to the
622caller are \emph{borrowed} references; do not decrement their
623reference count!
624
Fred Drakecc8f44b2001-08-20 19:30:29 +0000625Some example calls:
626
627\begin{verbatim}
628 int ok;
629 int i, j;
630 long k, l;
631 char *s;
632 int size;
633
634 ok = PyArg_ParseTuple(args, ""); /* No arguments */
635 /* Python call: f() */
636\end{verbatim}
637
638\begin{verbatim}
639 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
640 /* Possible Python call: f('whoops!') */
641\end{verbatim}
642
643\begin{verbatim}
644 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
645 /* Possible Python call: f(1, 2, 'three') */
646\end{verbatim}
647
648\begin{verbatim}
649 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
650 /* A pair of ints and a string, whose size is also returned */
651 /* Possible Python call: f((1, 2), 'three') */
652\end{verbatim}
653
654\begin{verbatim}
655 {
656 char *file;
657 char *mode = "r";
658 int bufsize = 0;
659 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
660 /* A string, and optionally another string and an integer */
661 /* Possible Python calls:
662 f('spam')
663 f('spam', 'w')
664 f('spam', 'wb', 100000) */
665 }
666\end{verbatim}
667
668\begin{verbatim}
669 {
670 int left, top, right, bottom, h, v;
671 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
672 &left, &top, &right, &bottom, &h, &v);
673 /* A rectangle and a point */
674 /* Possible Python call:
675 f(((0, 0), (400, 300)), (10, 10)) */
676 }
677\end{verbatim}
678
679\begin{verbatim}
680 {
681 Py_complex c;
682 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
683 /* a complex, also providing a function name for errors */
684 /* Possible Python call: myfunction(1+2j) */
685 }
686\end{verbatim}
687
688
689\section{Keyword Parameters for Extension Functions
690 \label{parseTupleAndKeywords}}
691
Fred Drakee9fba912002-03-28 22:36:56 +0000692\ttindex{PyArg_ParseTupleAndKeywords()}
693
Fred Drakecc8f44b2001-08-20 19:30:29 +0000694The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
695follows:
696
697\begin{verbatim}
698int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
699 char *format, char **kwlist, ...);
700\end{verbatim}
701
702The \var{arg} and \var{format} parameters are identical to those of the
703\cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
704is the dictionary of keywords received as the third parameter from the
Fred Drakec37b65e2001-11-28 07:26:15 +0000705Python runtime. The \var{kwlist} parameter is a \NULL-terminated
Fred Drakecc8f44b2001-08-20 19:30:29 +0000706list of strings which identify the parameters; the names are matched
707with the type information from \var{format} from left to right. On
708success, \cfunction{PyArg_ParseTupleAndKeywords()} returns true,
709otherwise it returns false and raises an appropriate exception.
710
Fred Drake0aa811c2001-10-20 04:24:09 +0000711\note{Nested tuples cannot be parsed when using keyword
Fred Drakecc8f44b2001-08-20 19:30:29 +0000712arguments! Keyword parameters passed in which are not present in the
Fred Drake0aa811c2001-10-20 04:24:09 +0000713\var{kwlist} will cause \exception{TypeError} to be raised.}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000714
715Here is an example module which uses keywords, based on an example by
716Geoff Philbrick (\email{philbrick@hks.com}):%
717\index{Philbrick, Geoff}
718
719\begin{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000720#include "Python.h"
721
722static PyObject *
723keywdarg_parrot(self, args, keywds)
724 PyObject *self;
725 PyObject *args;
726 PyObject *keywds;
727{
728 int voltage;
729 char *state = "a stiff";
730 char *action = "voom";
731 char *type = "Norwegian Blue";
732
733 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
734
735 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
736 &voltage, &state, &action, &type))
737 return NULL;
738
739 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
740 action, voltage);
741 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
742
743 Py_INCREF(Py_None);
744
745 return Py_None;
746}
747
748static PyMethodDef keywdarg_methods[] = {
749 /* The cast of the function is necessary since PyCFunction values
750 * only take two PyObject* parameters, and keywdarg_parrot() takes
751 * three.
752 */
Fred Drake31f84832002-03-28 20:19:23 +0000753 {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
Fred Drakeef6373a2001-11-17 06:50:42 +0000754 "Print a lovely skit to standard output."},
755 {NULL, NULL, 0, NULL} /* sentinel */
Fred Drakecc8f44b2001-08-20 19:30:29 +0000756};
Fred Drake31f84832002-03-28 20:19:23 +0000757\end{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000758
Fred Drake31f84832002-03-28 20:19:23 +0000759\begin{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000760void
Fred Drakeef6373a2001-11-17 06:50:42 +0000761initkeywdarg(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +0000762{
763 /* Create the module and add the functions */
764 Py_InitModule("keywdarg", keywdarg_methods);
765}
766\end{verbatim}
767
768
769\section{Building Arbitrary Values
770 \label{buildValue}}
771
772This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
773declared as follows:
774
775\begin{verbatim}
776PyObject *Py_BuildValue(char *format, ...);
777\end{verbatim}
778
779It recognizes a set of format units similar to the ones recognized by
780\cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
781function, not output) must not be pointers, just values. It returns a
782new Python object, suitable for returning from a C function called
783from Python.
784
785One difference with \cfunction{PyArg_ParseTuple()}: while the latter
786requires its first argument to be a tuple (since Python argument lists
787are always represented as tuples internally),
788\cfunction{Py_BuildValue()} does not always build a tuple. It builds
789a tuple only if its format string contains two or more format units.
790If the format string is empty, it returns \code{None}; if it contains
791exactly one format unit, it returns whatever object is described by
792that format unit. To force it to return a tuple of size 0 or one,
793parenthesize the format string.
794
Fred Drakecc8f44b2001-08-20 19:30:29 +0000795Examples (to the left the call, to the right the resulting Python value):
796
797\begin{verbatim}
798 Py_BuildValue("") None
799 Py_BuildValue("i", 123) 123
800 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
801 Py_BuildValue("s", "hello") 'hello'
802 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
803 Py_BuildValue("s#", "hello", 4) 'hell'
804 Py_BuildValue("()") ()
805 Py_BuildValue("(i)", 123) (123,)
806 Py_BuildValue("(ii)", 123, 456) (123, 456)
807 Py_BuildValue("(i,i)", 123, 456) (123, 456)
808 Py_BuildValue("[i,i]", 123, 456) [123, 456]
809 Py_BuildValue("{s:i,s:i}",
810 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
811 Py_BuildValue("((ii)(ii)) (ii)",
812 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
813\end{verbatim}
814
815
816\section{Reference Counts
817 \label{refcounts}}
818
Fred Drakec37b65e2001-11-28 07:26:15 +0000819In languages like C or \Cpp, the programmer is responsible for
Fred Drakecc8f44b2001-08-20 19:30:29 +0000820dynamic allocation and deallocation of memory on the heap. In C,
821this is done using the functions \cfunction{malloc()} and
Fred Drakec37b65e2001-11-28 07:26:15 +0000822\cfunction{free()}. In \Cpp, the operators \keyword{new} and
Fred Drakecc8f44b2001-08-20 19:30:29 +0000823\keyword{delete} are used with essentially the same meaning; they are
824actually implemented using \cfunction{malloc()} and
825\cfunction{free()}, so we'll restrict the following discussion to the
826latter.
827
828Every block of memory allocated with \cfunction{malloc()} should
829eventually be returned to the pool of available memory by exactly one
830call to \cfunction{free()}. It is important to call
831\cfunction{free()} at the right time. If a block's address is
832forgotten but \cfunction{free()} is not called for it, the memory it
833occupies cannot be reused until the program terminates. This is
834called a \dfn{memory leak}. On the other hand, if a program calls
835\cfunction{free()} for a block and then continues to use the block, it
836creates a conflict with re-use of the block through another
837\cfunction{malloc()} call. This is called \dfn{using freed memory}.
838It has the same bad consequences as referencing uninitialized data ---
839core dumps, wrong results, mysterious crashes.
840
841Common causes of memory leaks are unusual paths through the code. For
842instance, a function may allocate a block of memory, do some
843calculation, and then free the block again. Now a change in the
844requirements for the function may add a test to the calculation that
845detects an error condition and can return prematurely from the
846function. It's easy to forget to free the allocated memory block when
847taking this premature exit, especially when it is added later to the
848code. Such leaks, once introduced, often go undetected for a long
849time: the error exit is taken only in a small fraction of all calls,
850and most modern machines have plenty of virtual memory, so the leak
851only becomes apparent in a long-running process that uses the leaking
852function frequently. Therefore, it's important to prevent leaks from
853happening by having a coding convention or strategy that minimizes
854this kind of errors.
855
856Since Python makes heavy use of \cfunction{malloc()} and
857\cfunction{free()}, it needs a strategy to avoid memory leaks as well
858as the use of freed memory. The chosen method is called
859\dfn{reference counting}. The principle is simple: every object
860contains a counter, which is incremented when a reference to the
861object is stored somewhere, and which is decremented when a reference
862to it is deleted. When the counter reaches zero, the last reference
863to the object has been deleted and the object is freed.
864
865An alternative strategy is called \dfn{automatic garbage collection}.
866(Sometimes, reference counting is also referred to as a garbage
867collection strategy, hence my use of ``automatic'' to distinguish the
868two.) The big advantage of automatic garbage collection is that the
869user doesn't need to call \cfunction{free()} explicitly. (Another claimed
870advantage is an improvement in speed or memory usage --- this is no
871hard fact however.) The disadvantage is that for C, there is no
872truly portable automatic garbage collector, while reference counting
873can be implemented portably (as long as the functions \cfunction{malloc()}
874and \cfunction{free()} are available --- which the C Standard guarantees).
875Maybe some day a sufficiently portable automatic garbage collector
876will be available for C. Until then, we'll have to live with
877reference counts.
878
Fred Drake024e6472001-12-07 17:30:40 +0000879While Python uses the traditional reference counting implementation,
880it also offers a cycle detector that works to detect reference
881cycles. This allows applications to not worry about creating direct
882or indirect circular references; these are the weakness of garbage
883collection implemented using only reference counting. Reference
884cycles consist of objects which contain (possibly indirect) references
Tim Peters874c4f02001-12-07 17:51:41 +0000885to themselves, so that each object in the cycle has a reference count
Fred Drake024e6472001-12-07 17:30:40 +0000886which is non-zero. Typical reference counting implementations are not
Tim Peters874c4f02001-12-07 17:51:41 +0000887able to reclaim the memory belonging to any objects in a reference
Fred Drake024e6472001-12-07 17:30:40 +0000888cycle, or referenced from the objects in the cycle, even though there
889are no further references to the cycle itself.
890
891The cycle detector is able to detect garbage cycles and can reclaim
892them so long as there are no finalizers implemented in Python
893(\method{__del__()} methods). When there are such finalizers, the
894detector exposes the cycles through the \ulink{\module{gc}
Guido van Rossum44b3f762001-12-07 17:57:56 +0000895module}{../lib/module-gc.html} (specifically, the \code{garbage}
896variable in that module). The \module{gc} module also exposes a way
897to run the detector (the \function{collect()} function), as well as
Fred Drake024e6472001-12-07 17:30:40 +0000898configuration interfaces and the ability to disable the detector at
899runtime. The cycle detector is considered an optional component;
Guido van Rossum44b3f762001-12-07 17:57:56 +0000900though it is included by default, it can be disabled at build time
Fred Drake024e6472001-12-07 17:30:40 +0000901using the \longprogramopt{without-cycle-gc} option to the
902\program{configure} script on \UNIX{} platforms (including Mac OS X)
903or by removing the definition of \code{WITH_CYCLE_GC} in the
904\file{pyconfig.h} header on other platforms. If the cycle detector is
905disabled in this way, the \module{gc} module will not be available.
906
907
Fred Drakecc8f44b2001-08-20 19:30:29 +0000908\subsection{Reference Counting in Python
909 \label{refcountsInPython}}
910
911There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
912which handle the incrementing and decrementing of the reference count.
913\cfunction{Py_DECREF()} also frees the object when the count reaches zero.
914For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
915makes a call through a function pointer in the object's \dfn{type
916object}. For this purpose (and others), every object also contains a
917pointer to its type object.
918
919The big question now remains: when to use \code{Py_INCREF(x)} and
920\code{Py_DECREF(x)}? Let's first introduce some terms. Nobody
921``owns'' an object; however, you can \dfn{own a reference} to an
922object. An object's reference count is now defined as the number of
923owned references to it. The owner of a reference is responsible for
924calling \cfunction{Py_DECREF()} when the reference is no longer
925needed. Ownership of a reference can be transferred. There are three
926ways to dispose of an owned reference: pass it on, store it, or call
927\cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
928creates a memory leak.
929
930It is also possible to \dfn{borrow}\footnote{The metaphor of
931``borrowing'' a reference is not completely correct: the owner still
932has a copy of the reference.} a reference to an object. The borrower
933of a reference should not call \cfunction{Py_DECREF()}. The borrower must
934not hold on to the object longer than the owner from which it was
935borrowed. Using a borrowed reference after the owner has disposed of
936it risks using freed memory and should be avoided
937completely.\footnote{Checking that the reference count is at least 1
938\strong{does not work} --- the reference count itself could be in
939freed memory and may thus be reused for another object!}
940
941The advantage of borrowing over owning a reference is that you don't
942need to take care of disposing of the reference on all possible paths
943through the code --- in other words, with a borrowed reference you
944don't run the risk of leaking when a premature exit is taken. The
945disadvantage of borrowing over leaking is that there are some subtle
946situations where in seemingly correct code a borrowed reference can be
947used after the owner from which it was borrowed has in fact disposed
948of it.
949
950A borrowed reference can be changed into an owned reference by calling
951\cfunction{Py_INCREF()}. This does not affect the status of the owner from
952which the reference was borrowed --- it creates a new owned reference,
953and gives full owner responsibilities (the new owner must
954dispose of the reference properly, as well as the previous owner).
955
956
957\subsection{Ownership Rules
958 \label{ownershipRules}}
959
960Whenever an object reference is passed into or out of a function, it
961is part of the function's interface specification whether ownership is
962transferred with the reference or not.
963
964Most functions that return a reference to an object pass on ownership
965with the reference. In particular, all functions whose function it is
966to create a new object, such as \cfunction{PyInt_FromLong()} and
Fred Drake92024d12001-11-29 07:16:19 +0000967\cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if
968the object is not actually new, you still receive ownership of a new
969reference to that object. For instance, \cfunction{PyInt_FromLong()}
970maintains a cache of popular values and can return a reference to a
971cached item.
Fred Drakecc8f44b2001-08-20 19:30:29 +0000972
973Many functions that extract objects from other objects also transfer
974ownership with the reference, for instance
975\cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
976however, since a few common routines are exceptions:
977\cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
978\cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
979all return references that you borrow from the tuple, list or
980dictionary.
981
982The function \cfunction{PyImport_AddModule()} also returns a borrowed
983reference, even though it may actually create the object it returns:
984this is possible because an owned reference to the object is stored in
985\code{sys.modules}.
986
987When you pass an object reference into another function, in general,
988the function borrows the reference from you --- if it needs to store
989it, it will use \cfunction{Py_INCREF()} to become an independent
990owner. There are exactly two important exceptions to this rule:
991\cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
992functions take over ownership of the item passed to them --- even if
993they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
994take over ownership --- they are ``normal.'')
995
996When a C function is called from Python, it borrows references to its
997arguments from the caller. The caller owns a reference to the object,
998so the borrowed reference's lifetime is guaranteed until the function
999returns. Only when such a borrowed reference must be stored or passed
1000on, it must be turned into an owned reference by calling
1001\cfunction{Py_INCREF()}.
1002
1003The object reference returned from a C function that is called from
1004Python must be an owned reference --- ownership is tranferred from the
1005function to its caller.
1006
1007
1008\subsection{Thin Ice
1009 \label{thinIce}}
1010
1011There are a few situations where seemingly harmless use of a borrowed
1012reference can lead to problems. These all have to do with implicit
1013invocations of the interpreter, which can cause the owner of a
1014reference to dispose of it.
1015
1016The first and most important case to know about is using
1017\cfunction{Py_DECREF()} on an unrelated object while borrowing a
1018reference to a list item. For instance:
1019
1020\begin{verbatim}
1021bug(PyObject *list) {
1022 PyObject *item = PyList_GetItem(list, 0);
1023
1024 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1025 PyObject_Print(item, stdout, 0); /* BUG! */
1026}
1027\end{verbatim}
1028
1029This function first borrows a reference to \code{list[0]}, then
1030replaces \code{list[1]} with the value \code{0}, and finally prints
1031the borrowed reference. Looks harmless, right? But it's not!
1032
1033Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
1034owns references to all its items, so when item 1 is replaced, it has
1035to dispose of the original item 1. Now let's suppose the original
1036item 1 was an instance of a user-defined class, and let's further
1037suppose that the class defined a \method{__del__()} method. If this
1038class instance has a reference count of 1, disposing of it will call
1039its \method{__del__()} method.
1040
1041Since it is written in Python, the \method{__del__()} method can execute
1042arbitrary Python code. Could it perhaps do something to invalidate
1043the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
1044that the list passed into \cfunction{bug()} is accessible to the
1045\method{__del__()} method, it could execute a statement to the effect of
1046\samp{del list[0]}, and assuming this was the last reference to that
1047object, it would free the memory associated with it, thereby
1048invalidating \code{item}.
1049
1050The solution, once you know the source of the problem, is easy:
1051temporarily increment the reference count. The correct version of the
1052function reads:
1053
1054\begin{verbatim}
1055no_bug(PyObject *list) {
1056 PyObject *item = PyList_GetItem(list, 0);
1057
1058 Py_INCREF(item);
1059 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1060 PyObject_Print(item, stdout, 0);
1061 Py_DECREF(item);
1062}
1063\end{verbatim}
1064
1065This is a true story. An older version of Python contained variants
1066of this bug and someone spent a considerable amount of time in a C
1067debugger to figure out why his \method{__del__()} methods would fail...
1068
1069The second case of problems with a borrowed reference is a variant
1070involving threads. Normally, multiple threads in the Python
1071interpreter can't get in each other's way, because there is a global
1072lock protecting Python's entire object space. However, it is possible
1073to temporarily release this lock using the macro
Fred Drake375e3022002-04-09 21:09:42 +00001074\csimplemacro{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
1075\csimplemacro{Py_END_ALLOW_THREADS}. This is common around blocking
1076I/O calls, to let other threads use the processor while waiting for
1077the I/O to complete. Obviously, the following function has the same
1078problem as the previous one:
Fred Drakecc8f44b2001-08-20 19:30:29 +00001079
1080\begin{verbatim}
1081bug(PyObject *list) {
1082 PyObject *item = PyList_GetItem(list, 0);
1083 Py_BEGIN_ALLOW_THREADS
1084 ...some blocking I/O call...
1085 Py_END_ALLOW_THREADS
1086 PyObject_Print(item, stdout, 0); /* BUG! */
1087}
1088\end{verbatim}
1089
1090
1091\subsection{NULL Pointers
1092 \label{nullPointers}}
1093
1094In general, functions that take object references as arguments do not
1095expect you to pass them \NULL{} pointers, and will dump core (or
1096cause later core dumps) if you do so. Functions that return object
1097references generally return \NULL{} only to indicate that an
1098exception occurred. The reason for not testing for \NULL{}
1099arguments is that functions often pass the objects they receive on to
Fred Drakec37b65e2001-11-28 07:26:15 +00001100other function --- if each function were to test for \NULL,
Fred Drakecc8f44b2001-08-20 19:30:29 +00001101there would be a lot of redundant tests and the code would run more
1102slowly.
1103
1104It is better to test for \NULL{} only at the ``source:'' when a
1105pointer that may be \NULL{} is received, for example, from
1106\cfunction{malloc()} or from a function that may raise an exception.
1107
1108The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
1109do not check for \NULL{} pointers --- however, their variants
1110\cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
1111
1112The macros for checking for a particular object type
1113(\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
1114again, there is much code that calls several of these in a row to test
1115an object against various different expected types, and this would
1116generate redundant tests. There are no variants with \NULL{}
1117checking.
1118
1119The C function calling mechanism guarantees that the argument list
1120passed to C functions (\code{args} in the examples) is never
1121\NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
1122These guarantees don't hold when you use the ``old'' style
1123calling convention --- this is still found in much existing code.}
1124
1125It is a severe error to ever let a \NULL{} pointer ``escape'' to
1126the Python user.
1127
1128% Frank Stajano:
1129% A pedagogically buggy example, along the lines of the previous listing,
1130% would be helpful here -- showing in more concrete terms what sort of
1131% actions could cause the problem. I can't very well imagine it from the
1132% description.
1133
1134
Fred Drakec37b65e2001-11-28 07:26:15 +00001135\section{Writing Extensions in \Cpp
Fred Drakecc8f44b2001-08-20 19:30:29 +00001136 \label{cplusplus}}
1137
Fred Drakec37b65e2001-11-28 07:26:15 +00001138It is possible to write extension modules in \Cpp. Some restrictions
Fred Drakecc8f44b2001-08-20 19:30:29 +00001139apply. If the main program (the Python interpreter) is compiled and
1140linked by the C compiler, global or static objects with constructors
1141cannot be used. This is not a problem if the main program is linked
1142by the \Cpp{} compiler. Functions that will be called by the
1143Python interpreter (in particular, module initalization functions)
1144have to be declared using \code{extern "C"}.
1145It is unnecessary to enclose the Python header files in
1146\code{extern "C" \{...\}} --- they use this form already if the symbol
1147\samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
1148symbol).
1149
1150
1151\section{Providing a C API for an Extension Module
1152 \label{using-cobjects}}
1153\sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
1154
1155Many extension modules just provide new functions and types to be
1156used from Python, but sometimes the code in an extension module can
1157be useful for other extension modules. For example, an extension
1158module could implement a type ``collection'' which works like lists
1159without order. Just like the standard Python list type has a C API
1160which permits extension modules to create and manipulate lists, this
1161new collection type should have a set of C functions for direct
1162manipulation from other extension modules.
1163
1164At first sight this seems easy: just write the functions (without
1165declaring them \keyword{static}, of course), provide an appropriate
1166header file, and document the C API. And in fact this would work if
1167all extension modules were always linked statically with the Python
1168interpreter. When modules are used as shared libraries, however, the
1169symbols defined in one module may not be visible to another module.
1170The details of visibility depend on the operating system; some systems
1171use one global namespace for the Python interpreter and all extension
1172modules (Windows, for example), whereas others require an explicit
1173list of imported symbols at module link time (AIX is one example), or
1174offer a choice of different strategies (most Unices). And even if
1175symbols are globally visible, the module whose functions one wishes to
1176call might not have been loaded yet!
1177
1178Portability therefore requires not to make any assumptions about
1179symbol visibility. This means that all symbols in extension modules
1180should be declared \keyword{static}, except for the module's
1181initialization function, in order to avoid name clashes with other
1182extension modules (as discussed in section~\ref{methodTable}). And it
1183means that symbols that \emph{should} be accessible from other
1184extension modules must be exported in a different way.
1185
1186Python provides a special mechanism to pass C-level information
1187(pointers) from one extension module to another one: CObjects.
1188A CObject is a Python data type which stores a pointer (\ctype{void
1189*}). CObjects can only be created and accessed via their C API, but
1190they can be passed around like any other Python object. In particular,
1191they can be assigned to a name in an extension module's namespace.
1192Other extension modules can then import this module, retrieve the
1193value of this name, and then retrieve the pointer from the CObject.
1194
1195There are many ways in which CObjects can be used to export the C API
1196of an extension module. Each name could get its own CObject, or all C
1197API pointers could be stored in an array whose address is published in
1198a CObject. And the various tasks of storing and retrieving the pointers
1199can be distributed in different ways between the module providing the
1200code and the client modules.
1201
1202The following example demonstrates an approach that puts most of the
1203burden on the writer of the exporting module, which is appropriate
1204for commonly used library modules. It stores all C API pointers
1205(just one in the example!) in an array of \ctype{void} pointers which
1206becomes the value of a CObject. The header file corresponding to
1207the module provides a macro that takes care of importing the module
1208and retrieving its C API pointers; client modules only have to call
1209this macro before accessing the C API.
1210
1211The exporting module is a modification of the \module{spam} module from
1212section~\ref{simpleExample}. The function \function{spam.system()}
1213does not call the C library function \cfunction{system()} directly,
1214but a function \cfunction{PySpam_System()}, which would of course do
1215something more complicated in reality (such as adding ``spam'' to
1216every command). This function \cfunction{PySpam_System()} is also
1217exported to other extension modules.
1218
1219The function \cfunction{PySpam_System()} is a plain C function,
1220declared \keyword{static} like everything else:
1221
1222\begin{verbatim}
1223static int
1224PySpam_System(command)
1225 char *command;
1226{
1227 return system(command);
1228}
1229\end{verbatim}
1230
1231The function \cfunction{spam_system()} is modified in a trivial way:
1232
1233\begin{verbatim}
1234static PyObject *
1235spam_system(self, args)
1236 PyObject *self;
1237 PyObject *args;
1238{
1239 char *command;
1240 int sts;
1241
1242 if (!PyArg_ParseTuple(args, "s", &command))
1243 return NULL;
1244 sts = PySpam_System(command);
1245 return Py_BuildValue("i", sts);
1246}
1247\end{verbatim}
1248
1249In the beginning of the module, right after the line
1250
1251\begin{verbatim}
1252#include "Python.h"
1253\end{verbatim}
1254
1255two more lines must be added:
1256
1257\begin{verbatim}
1258#define SPAM_MODULE
1259#include "spammodule.h"
1260\end{verbatim}
1261
1262The \code{\#define} is used to tell the header file that it is being
1263included in the exporting module, not a client module. Finally,
1264the module's initialization function must take care of initializing
1265the C API pointer array:
1266
1267\begin{verbatim}
1268void
Fred Drakeef6373a2001-11-17 06:50:42 +00001269initspam(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +00001270{
1271 PyObject *m;
1272 static void *PySpam_API[PySpam_API_pointers];
1273 PyObject *c_api_object;
1274
1275 m = Py_InitModule("spam", SpamMethods);
1276
1277 /* Initialize the C API pointer array */
1278 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1279
1280 /* Create a CObject containing the API pointer array's address */
1281 c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
1282
Fred Drake63e40a52002-04-12 19:08:31 +00001283 if (c_api_object != NULL)
1284 PyModule_AddObject(m, "_C_API", c_api_object);
Fred Drakecc8f44b2001-08-20 19:30:29 +00001285}
1286\end{verbatim}
1287
Fred Drakeef6373a2001-11-17 06:50:42 +00001288Note that \code{PySpam_API} is declared \keyword{static}; otherwise
1289the pointer array would disappear when \function{initspam()} terminates!
Fred Drakecc8f44b2001-08-20 19:30:29 +00001290
1291The bulk of the work is in the header file \file{spammodule.h},
1292which looks like this:
1293
1294\begin{verbatim}
1295#ifndef Py_SPAMMODULE_H
1296#define Py_SPAMMODULE_H
1297#ifdef __cplusplus
1298extern "C" {
1299#endif
1300
1301/* Header file for spammodule */
1302
1303/* C API functions */
1304#define PySpam_System_NUM 0
1305#define PySpam_System_RETURN int
1306#define PySpam_System_PROTO (char *command)
1307
1308/* Total number of C API pointers */
1309#define PySpam_API_pointers 1
1310
1311
1312#ifdef SPAM_MODULE
1313/* This section is used when compiling spammodule.c */
1314
1315static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1316
1317#else
1318/* This section is used in modules that use spammodule's API */
1319
1320static void **PySpam_API;
1321
1322#define PySpam_System \
1323 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1324
Fred Drake63e40a52002-04-12 19:08:31 +00001325/* Return -1 and set exception on error, 0 on success. */
1326static int
1327import_spam(void)
1328{
1329 PyObject *module = PyImport_ImportModule("spam");
1330
1331 if (module != NULL) {
1332 PyObject *c_api_object = PyObject_GetAttrString(module, "_C_API");
1333 if (c_api_object == NULL)
1334 return -1;
1335 if (PyCObject_Check(c_api_object))
1336 PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object);
1337 Py_DECREF(c_api_object);
1338 }
1339 return 0;
Fred Drakecc8f44b2001-08-20 19:30:29 +00001340}
1341
1342#endif
1343
1344#ifdef __cplusplus
1345}
1346#endif
1347
1348#endif /* !defined(Py_SPAMMODULE_H */
1349\end{verbatim}
1350
1351All that a client module must do in order to have access to the
1352function \cfunction{PySpam_System()} is to call the function (or
1353rather macro) \cfunction{import_spam()} in its initialization
1354function:
1355
1356\begin{verbatim}
1357void
Fred Drakeef6373a2001-11-17 06:50:42 +00001358initclient(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +00001359{
1360 PyObject *m;
1361
1362 Py_InitModule("client", ClientMethods);
Fred Drake63e40a52002-04-12 19:08:31 +00001363 if (import_spam() < 0)
1364 return;
1365 /* additional initialization can happen here */
Fred Drakecc8f44b2001-08-20 19:30:29 +00001366}
1367\end{verbatim}
1368
1369The main disadvantage of this approach is that the file
1370\file{spammodule.h} is rather complicated. However, the
1371basic structure is the same for each function that is
1372exported, so it has to be learned only once.
1373
1374Finally it should be mentioned that CObjects offer additional
1375functionality, which is especially useful for memory allocation and
1376deallocation of the pointer stored in a CObject. The details
1377are described in the \citetitle[../api/api.html]{Python/C API
Fred Drake63e40a52002-04-12 19:08:31 +00001378Reference Manual} in the section
1379``\ulink{CObjects}{../api/cObjects.html}'' and in the implementation
1380of CObjects (files \file{Include/cobject.h} and
Fred Drakecc8f44b2001-08-20 19:30:29 +00001381\file{Objects/cobject.c} in the Python source code distribution).