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