blob: 783137a61b150be1c25fcaf8fd52c018b4e1cbbd [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
605must be a format string, whose syntax is explained below. The
606remaining arguments must be addresses of variables whose type is
607determined by the format string. For the conversion to succeed, the
608\var{arg} object must match the format and the format must be
609exhausted. On success, \cfunction{PyArg_ParseTuple()} returns true,
610otherwise it returns false and raises an appropriate exception.
611
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
618A format string consists of zero or more ``format units''. A format
619unit describes one Python object; it is usually a single character or
620a parenthesized sequence of format units. With a few exceptions, a
621format unit that is not a parenthesized sequence normally corresponds
622to a single address argument to \cfunction{PyArg_ParseTuple()}. In the
623following description, the quoted form is the format unit; the entry
624in (round) parentheses is the Python object type that matches the
625format unit; and the entry in [square] brackets is the type of the C
626variable(s) whose address should be passed. (Use the \samp{\&}
627operator to pass a variable's address.)
628
629Note that any Python object references which are provided to the
630caller are \emph{borrowed} references; do not decrement their
631reference count!
632
633\begin{description}
634
635\item[\samp{s} (string or Unicode object) {[char *]}]
636Convert a Python string or Unicode object to a C pointer to a
637character string. You must not provide storage for the string
638itself; a pointer to an existing string is stored into the character
639pointer variable whose address you pass. The C string is
640null-terminated. The Python string must not contain embedded null
641bytes; if it does, a \exception{TypeError} exception is raised.
642Unicode objects are converted to C strings using the default
643encoding. If this conversion fails, an \exception{UnicodeError} is
644raised.
645
646\item[\samp{s\#} (string, Unicode or any read buffer compatible object)
647{[char *, int]}]
648This variant on \samp{s} stores into two C variables, the first one a
649pointer to a character string, the second one its length. In this
650case the Python string may contain embedded null bytes. Unicode
651objects pass back a pointer to the default encoded string version of the
652object if such a conversion is possible. All other read buffer
653compatible objects pass back a reference to the raw internal data
654representation.
655
656\item[\samp{z} (string or \code{None}) {[char *]}]
657Like \samp{s}, but the Python object may also be \code{None}, in which
Fred Drakec37b65e2001-11-28 07:26:15 +0000658case the C pointer is set to \NULL.
Fred Drakecc8f44b2001-08-20 19:30:29 +0000659
660\item[\samp{z\#} (string or \code{None} or any read buffer compatible object)
661{[char *, int]}]
662This is to \samp{s\#} as \samp{z} is to \samp{s}.
663
664\item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
665Convert a Python Unicode object to a C pointer to a null-terminated
666buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need
667to provide storage for the Unicode data buffer; a pointer to the
668existing Unicode data is stored into the Py_UNICODE pointer variable whose
669address you pass.
670
671\item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
672This variant on \samp{u} stores into two C variables, the first one
673a pointer to a Unicode data buffer, the second one its length.
Marc-André Lemburg3e3eacb2002-01-09 16:21:27 +0000674Non-Unicode objects are handled by interpreting their read buffer
675pointer as pointer to a Py_UNICODE array.
Fred Drakecc8f44b2001-08-20 19:30:29 +0000676
677\item[\samp{es} (string, Unicode object or character buffer compatible
678object) {[const char *encoding, char **buffer]}]
679This variant on \samp{s} is used for encoding Unicode and objects
680convertible to Unicode into a character buffer. It only works for
681encoded data without embedded \NULL{} bytes.
682
683The variant reads one C variable and stores into two C variables, the
684first one a pointer to an encoding name string (\var{encoding}), and the
685second a pointer to a pointer to a character buffer (\var{**buffer},
686the buffer used for storing the encoded data).
687
Fred Drakec37b65e2001-11-28 07:26:15 +0000688The encoding name must map to a registered codec. If set to \NULL,
Fred Drakecc8f44b2001-08-20 19:30:29 +0000689the default encoding is used.
690
691\cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
692size using \cfunction{PyMem_NEW()}, copy the encoded data into this
693buffer and adjust \var{*buffer} to reference the newly allocated
694storage. The caller is responsible for calling
695\cfunction{PyMem_Free()} to free the allocated buffer after usage.
696
697\item[\samp{et} (string, Unicode object or character buffer compatible
698object) {[const char *encoding, char **buffer]}]
699Same as \samp{es} except that string objects are passed through without
700recoding them. Instead, the implementation assumes that the string
701object uses the encoding passed in as parameter.
702
703\item[\samp{es\#} (string, Unicode object or character buffer compatible
704object) {[const char *encoding, char **buffer, int *buffer_length]}]
705This variant on \samp{s\#} is used for encoding Unicode and objects
706convertible to Unicode into a character buffer. It reads one C
707variable and stores into three C variables, the first one a pointer to
708an encoding name string (\var{encoding}), the second a pointer to a
709pointer to a character buffer (\var{**buffer}, the buffer used for
710storing the encoded data) and the third one a pointer to an integer
711(\var{*buffer_length}, the buffer length).
712
Fred Drakec37b65e2001-11-28 07:26:15 +0000713The encoding name must map to a registered codec. If set to \NULL,
Fred Drakecc8f44b2001-08-20 19:30:29 +0000714the default encoding is used.
715
716There are two modes of operation:
717
718If \var{*buffer} points a \NULL{} pointer,
719\cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
720size using \cfunction{PyMem_NEW()}, copy the encoded data into this
721buffer and adjust \var{*buffer} to reference the newly allocated
722storage. The caller is responsible for calling
723\cfunction{PyMem_Free()} to free the allocated buffer after usage.
724
725If \var{*buffer} points to a non-\NULL{} pointer (an already allocated
726buffer), \cfunction{PyArg_ParseTuple()} will use this location as
727buffer and interpret \var{*buffer_length} as buffer size. It will then
728copy the encoded data into the buffer and 0-terminate it. Buffer
729overflow is signalled with an exception.
730
731In both cases, \var{*buffer_length} is set to the length of the
732encoded data without the trailing 0-byte.
733
734\item[\samp{et\#} (string, Unicode object or character buffer compatible
735object) {[const char *encoding, char **buffer]}]
736Same as \samp{es\#} except that string objects are passed through without
737recoding them. Instead, the implementation assumes that the string
738object uses the encoding passed in as parameter.
739
740\item[\samp{b} (integer) {[char]}]
741Convert a Python integer to a tiny int, stored in a C \ctype{char}.
742
743\item[\samp{h} (integer) {[short int]}]
744Convert a Python integer to a C \ctype{short int}.
745
746\item[\samp{i} (integer) {[int]}]
747Convert a Python integer to a plain C \ctype{int}.
748
749\item[\samp{l} (integer) {[long int]}]
750Convert a Python integer to a C \ctype{long int}.
751
Tim Petersd38b1c72001-09-30 05:09:37 +0000752\item[\samp{L} (integer) {[LONG_LONG]}]
753Convert a Python integer to a C \ctype{long long}. This format is only
754available on platforms that support \ctype{long long} (or \ctype{_int64}
755on Windows).
756
Fred Drakecc8f44b2001-08-20 19:30:29 +0000757\item[\samp{c} (string of length 1) {[char]}]
758Convert a Python character, represented as a string of length 1, to a
759C \ctype{char}.
760
761\item[\samp{f} (float) {[float]}]
762Convert a Python floating point number to a C \ctype{float}.
763
764\item[\samp{d} (float) {[double]}]
765Convert a Python floating point number to a C \ctype{double}.
766
767\item[\samp{D} (complex) {[Py_complex]}]
768Convert a Python complex number to a C \ctype{Py_complex} structure.
769
770\item[\samp{O} (object) {[PyObject *]}]
771Store a Python object (without any conversion) in a C object pointer.
772The C program thus receives the actual object that was passed. The
773object's reference count is not increased. The pointer stored is not
Fred Drakec37b65e2001-11-28 07:26:15 +0000774\NULL.
Fred Drakecc8f44b2001-08-20 19:30:29 +0000775
776\item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
777Store a Python object in a C object pointer. This is similar to
778\samp{O}, but takes two C arguments: the first is the address of a
779Python type object, the second is the address of the C variable (of
780type \ctype{PyObject *}) into which the object pointer is stored.
781If the Python object does not have the required type,
782\exception{TypeError} is raised.
783
784\item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
785Convert a Python object to a C variable through a \var{converter}
786function. This takes two arguments: the first is a function, the
787second is the address of a C variable (of arbitrary type), converted
788to \ctype{void *}. The \var{converter} function in turn is called as
789follows:
790
791\var{status}\code{ = }\var{converter}\code{(}\var{object}, \var{address}\code{);}
792
793where \var{object} is the Python object to be converted and
794\var{address} is the \ctype{void *} argument that was passed to
795\cfunction{PyArg_ConvertTuple()}. The returned \var{status} should be
796\code{1} for a successful conversion and \code{0} if the conversion
797has failed. When the conversion fails, the \var{converter} function
798should raise an exception.
799
800\item[\samp{S} (string) {[PyStringObject *]}]
801Like \samp{O} but requires that the Python object is a string object.
802Raises \exception{TypeError} if the object is not a string object.
803The C variable may also be declared as \ctype{PyObject *}.
804
805\item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
806Like \samp{O} but requires that the Python object is a Unicode object.
807Raises \exception{TypeError} if the object is not a Unicode object.
808The C variable may also be declared as \ctype{PyObject *}.
809
810\item[\samp{t\#} (read-only character buffer) {[char *, int]}]
811Like \samp{s\#}, but accepts any object which implements the read-only
812buffer interface. The \ctype{char *} variable is set to point to the
813first byte of the buffer, and the \ctype{int} is set to the length of
814the buffer. Only single-segment buffer objects are accepted;
815\exception{TypeError} is raised for all others.
816
817\item[\samp{w} (read-write character buffer) {[char *]}]
818Similar to \samp{s}, but accepts any object which implements the
819read-write buffer interface. The caller must determine the length of
820the buffer by other means, or use \samp{w\#} instead. Only
821single-segment buffer objects are accepted; \exception{TypeError} is
822raised for all others.
823
824\item[\samp{w\#} (read-write character buffer) {[char *, int]}]
825Like \samp{s\#}, but accepts any object which implements the
826read-write buffer interface. The \ctype{char *} variable is set to
827point to the first byte of the buffer, and the \ctype{int} is set to
828the length of the buffer. Only single-segment buffer objects are
829accepted; \exception{TypeError} is raised for all others.
830
831\item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
832The object must be a Python sequence whose length is the number of
833format units in \var{items}. The C arguments must correspond to the
834individual format units in \var{items}. Format units for sequences
835may be nested.
836
Fred Drake0aa811c2001-10-20 04:24:09 +0000837\note{Prior to Python version 1.5.2, this format specifier
Fred Drakecc8f44b2001-08-20 19:30:29 +0000838only accepted a tuple containing the individual parameters, not an
839arbitrary sequence. Code which previously caused
840\exception{TypeError} to be raised here may now proceed without an
Fred Drake0aa811c2001-10-20 04:24:09 +0000841exception. This is not expected to be a problem for existing code.}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000842
843\end{description}
844
845It is possible to pass Python long integers where integers are
846requested; however no proper range checking is done --- the most
847significant bits are silently truncated when the receiving field is
848too small to receive the value (actually, the semantics are inherited
849from downcasts in C --- your mileage may vary).
850
851A few other characters have a meaning in a format string. These may
852not occur inside nested parentheses. They are:
853
854\begin{description}
855
856\item[\samp{|}]
857Indicates that the remaining arguments in the Python argument list are
858optional. The C variables corresponding to optional arguments should
859be initialized to their default value --- when an optional argument is
860not specified, \cfunction{PyArg_ParseTuple()} does not touch the contents
861of the corresponding C variable(s).
862
863\item[\samp{:}]
864The list of format units ends here; the string after the colon is used
865as the function name in error messages (the ``associated value'' of
866the exception that \cfunction{PyArg_ParseTuple()} raises).
867
868\item[\samp{;}]
869The list of format units ends here; the string after the semicolon is
870used as the error message \emph{instead} of the default error message.
871Clearly, \samp{:} and \samp{;} mutually exclude each other.
872
873\end{description}
874
875Some example calls:
876
877\begin{verbatim}
878 int ok;
879 int i, j;
880 long k, l;
881 char *s;
882 int size;
883
884 ok = PyArg_ParseTuple(args, ""); /* No arguments */
885 /* Python call: f() */
886\end{verbatim}
887
888\begin{verbatim}
889 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
890 /* Possible Python call: f('whoops!') */
891\end{verbatim}
892
893\begin{verbatim}
894 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
895 /* Possible Python call: f(1, 2, 'three') */
896\end{verbatim}
897
898\begin{verbatim}
899 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
900 /* A pair of ints and a string, whose size is also returned */
901 /* Possible Python call: f((1, 2), 'three') */
902\end{verbatim}
903
904\begin{verbatim}
905 {
906 char *file;
907 char *mode = "r";
908 int bufsize = 0;
909 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
910 /* A string, and optionally another string and an integer */
911 /* Possible Python calls:
912 f('spam')
913 f('spam', 'w')
914 f('spam', 'wb', 100000) */
915 }
916\end{verbatim}
917
918\begin{verbatim}
919 {
920 int left, top, right, bottom, h, v;
921 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
922 &left, &top, &right, &bottom, &h, &v);
923 /* A rectangle and a point */
924 /* Possible Python call:
925 f(((0, 0), (400, 300)), (10, 10)) */
926 }
927\end{verbatim}
928
929\begin{verbatim}
930 {
931 Py_complex c;
932 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
933 /* a complex, also providing a function name for errors */
934 /* Possible Python call: myfunction(1+2j) */
935 }
936\end{verbatim}
937
938
939\section{Keyword Parameters for Extension Functions
940 \label{parseTupleAndKeywords}}
941
Fred Drakee9fba912002-03-28 22:36:56 +0000942\ttindex{PyArg_ParseTupleAndKeywords()}
943
Fred Drakecc8f44b2001-08-20 19:30:29 +0000944The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
945follows:
946
947\begin{verbatim}
948int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
949 char *format, char **kwlist, ...);
950\end{verbatim}
951
952The \var{arg} and \var{format} parameters are identical to those of the
953\cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
954is the dictionary of keywords received as the third parameter from the
Fred Drakec37b65e2001-11-28 07:26:15 +0000955Python runtime. The \var{kwlist} parameter is a \NULL-terminated
Fred Drakecc8f44b2001-08-20 19:30:29 +0000956list of strings which identify the parameters; the names are matched
957with the type information from \var{format} from left to right. On
958success, \cfunction{PyArg_ParseTupleAndKeywords()} returns true,
959otherwise it returns false and raises an appropriate exception.
960
Fred Drake0aa811c2001-10-20 04:24:09 +0000961\note{Nested tuples cannot be parsed when using keyword
Fred Drakecc8f44b2001-08-20 19:30:29 +0000962arguments! Keyword parameters passed in which are not present in the
Fred Drake0aa811c2001-10-20 04:24:09 +0000963\var{kwlist} will cause \exception{TypeError} to be raised.}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000964
965Here is an example module which uses keywords, based on an example by
966Geoff Philbrick (\email{philbrick@hks.com}):%
967\index{Philbrick, Geoff}
968
969\begin{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +0000970#include "Python.h"
971
972static PyObject *
973keywdarg_parrot(self, args, keywds)
974 PyObject *self;
975 PyObject *args;
976 PyObject *keywds;
977{
978 int voltage;
979 char *state = "a stiff";
980 char *action = "voom";
981 char *type = "Norwegian Blue";
982
983 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
984
985 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
986 &voltage, &state, &action, &type))
987 return NULL;
988
989 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
990 action, voltage);
991 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
992
993 Py_INCREF(Py_None);
994
995 return Py_None;
996}
997
998static PyMethodDef keywdarg_methods[] = {
999 /* The cast of the function is necessary since PyCFunction values
1000 * only take two PyObject* parameters, and keywdarg_parrot() takes
1001 * three.
1002 */
Fred Drake31f84832002-03-28 20:19:23 +00001003 {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
Fred Drakeef6373a2001-11-17 06:50:42 +00001004 "Print a lovely skit to standard output."},
1005 {NULL, NULL, 0, NULL} /* sentinel */
Fred Drakecc8f44b2001-08-20 19:30:29 +00001006};
Fred Drake31f84832002-03-28 20:19:23 +00001007\end{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +00001008
Fred Drake31f84832002-03-28 20:19:23 +00001009\begin{verbatim}
Fred Drakecc8f44b2001-08-20 19:30:29 +00001010void
Fred Drakeef6373a2001-11-17 06:50:42 +00001011initkeywdarg(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +00001012{
1013 /* Create the module and add the functions */
1014 Py_InitModule("keywdarg", keywdarg_methods);
1015}
1016\end{verbatim}
1017
1018
1019\section{Building Arbitrary Values
1020 \label{buildValue}}
1021
1022This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
1023declared as follows:
1024
1025\begin{verbatim}
1026PyObject *Py_BuildValue(char *format, ...);
1027\end{verbatim}
1028
1029It recognizes a set of format units similar to the ones recognized by
1030\cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
1031function, not output) must not be pointers, just values. It returns a
1032new Python object, suitable for returning from a C function called
1033from Python.
1034
1035One difference with \cfunction{PyArg_ParseTuple()}: while the latter
1036requires its first argument to be a tuple (since Python argument lists
1037are always represented as tuples internally),
1038\cfunction{Py_BuildValue()} does not always build a tuple. It builds
1039a tuple only if its format string contains two or more format units.
1040If the format string is empty, it returns \code{None}; if it contains
1041exactly one format unit, it returns whatever object is described by
1042that format unit. To force it to return a tuple of size 0 or one,
1043parenthesize the format string.
1044
1045When memory buffers are passed as parameters to supply data to build
1046objects, as for the \samp{s} and \samp{s\#} formats, the required data
1047is copied. Buffers provided by the caller are never referenced by the
1048objects created by \cfunction{Py_BuildValue()}. In other words, if
1049your code invokes \cfunction{malloc()} and passes the allocated memory
1050to \cfunction{Py_BuildValue()}, your code is responsible for
1051calling \cfunction{free()} for that memory once
1052\cfunction{Py_BuildValue()} returns.
1053
1054In the following description, the quoted form is the format unit; the
1055entry in (round) parentheses is the Python object type that the format
1056unit will return; and the entry in [square] brackets is the type of
1057the C value(s) to be passed.
1058
1059The characters space, tab, colon and comma are ignored in format
1060strings (but not within format units such as \samp{s\#}). This can be
1061used to make long format strings a tad more readable.
1062
1063\begin{description}
1064
1065\item[\samp{s} (string) {[char *]}]
1066Convert a null-terminated C string to a Python object. If the C
Fred Drakec37b65e2001-11-28 07:26:15 +00001067string pointer is \NULL, \code{None} is used.
Fred Drakecc8f44b2001-08-20 19:30:29 +00001068
1069\item[\samp{s\#} (string) {[char *, int]}]
1070Convert a C string and its length to a Python object. If the C string
Fred Drakec37b65e2001-11-28 07:26:15 +00001071pointer is \NULL, the length is ignored and \code{None} is
Fred Drakecc8f44b2001-08-20 19:30:29 +00001072returned.
1073
1074\item[\samp{z} (string or \code{None}) {[char *]}]
1075Same as \samp{s}.
1076
1077\item[\samp{z\#} (string or \code{None}) {[char *, int]}]
1078Same as \samp{s\#}.
1079
1080\item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1081Convert a null-terminated buffer of Unicode (UCS-2) data to a Python
1082Unicode object. If the Unicode buffer pointer is \NULL,
1083\code{None} is returned.
1084
1085\item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1086Convert a Unicode (UCS-2) data buffer and its length to a Python
1087Unicode object. If the Unicode buffer pointer is \NULL, the length
1088is ignored and \code{None} is returned.
1089
1090\item[\samp{i} (integer) {[int]}]
1091Convert a plain C \ctype{int} to a Python integer object.
1092
1093\item[\samp{b} (integer) {[char]}]
1094Same as \samp{i}.
1095
1096\item[\samp{h} (integer) {[short int]}]
1097Same as \samp{i}.
1098
1099\item[\samp{l} (integer) {[long int]}]
1100Convert a C \ctype{long int} to a Python integer object.
1101
1102\item[\samp{c} (string of length 1) {[char]}]
1103Convert a C \ctype{int} representing a character to a Python string of
1104length 1.
1105
1106\item[\samp{d} (float) {[double]}]
1107Convert a C \ctype{double} to a Python floating point number.
1108
1109\item[\samp{f} (float) {[float]}]
1110Same as \samp{d}.
1111
1112\item[\samp{D} (complex) {[Py_complex *]}]
1113Convert a C \ctype{Py_complex} structure to a Python complex number.
1114
1115\item[\samp{O} (object) {[PyObject *]}]
1116Pass a Python object untouched (except for its reference count, which
1117is incremented by one). If the object passed in is a \NULL{}
1118pointer, it is assumed that this was caused because the call producing
1119the argument found an error and set an exception. Therefore,
1120\cfunction{Py_BuildValue()} will return \NULL{} but won't raise an
1121exception. If no exception has been raised yet,
1122\cdata{PyExc_SystemError} is set.
1123
1124\item[\samp{S} (object) {[PyObject *]}]
1125Same as \samp{O}.
1126
1127\item[\samp{U} (object) {[PyObject *]}]
1128Same as \samp{O}.
1129
1130\item[\samp{N} (object) {[PyObject *]}]
1131Same as \samp{O}, except it doesn't increment the reference count on
1132the object. Useful when the object is created by a call to an object
1133constructor in the argument list.
1134
1135\item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
1136Convert \var{anything} to a Python object through a \var{converter}
1137function. The function is called with \var{anything} (which should be
1138compatible with \ctype{void *}) as its argument and should return a
1139``new'' Python object, or \NULL{} if an error occurred.
1140
1141\item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
1142Convert a sequence of C values to a Python tuple with the same number
1143of items.
1144
1145\item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
1146Convert a sequence of C values to a Python list with the same number
1147of items.
1148
1149\item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
1150Convert a sequence of C values to a Python dictionary. Each pair of
1151consecutive C values adds one item to the dictionary, serving as key
1152and value, respectively.
1153
1154\end{description}
1155
1156If there is an error in the format string, the
1157\cdata{PyExc_SystemError} exception is raised and \NULL{} returned.
1158
1159Examples (to the left the call, to the right the resulting Python value):
1160
1161\begin{verbatim}
1162 Py_BuildValue("") None
1163 Py_BuildValue("i", 123) 123
1164 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
1165 Py_BuildValue("s", "hello") 'hello'
1166 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
1167 Py_BuildValue("s#", "hello", 4) 'hell'
1168 Py_BuildValue("()") ()
1169 Py_BuildValue("(i)", 123) (123,)
1170 Py_BuildValue("(ii)", 123, 456) (123, 456)
1171 Py_BuildValue("(i,i)", 123, 456) (123, 456)
1172 Py_BuildValue("[i,i]", 123, 456) [123, 456]
1173 Py_BuildValue("{s:i,s:i}",
1174 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
1175 Py_BuildValue("((ii)(ii)) (ii)",
1176 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
1177\end{verbatim}
1178
1179
1180\section{Reference Counts
1181 \label{refcounts}}
1182
Fred Drakec37b65e2001-11-28 07:26:15 +00001183In languages like C or \Cpp, the programmer is responsible for
Fred Drakecc8f44b2001-08-20 19:30:29 +00001184dynamic allocation and deallocation of memory on the heap. In C,
1185this is done using the functions \cfunction{malloc()} and
Fred Drakec37b65e2001-11-28 07:26:15 +00001186\cfunction{free()}. In \Cpp, the operators \keyword{new} and
Fred Drakecc8f44b2001-08-20 19:30:29 +00001187\keyword{delete} are used with essentially the same meaning; they are
1188actually implemented using \cfunction{malloc()} and
1189\cfunction{free()}, so we'll restrict the following discussion to the
1190latter.
1191
1192Every block of memory allocated with \cfunction{malloc()} should
1193eventually be returned to the pool of available memory by exactly one
1194call to \cfunction{free()}. It is important to call
1195\cfunction{free()} at the right time. If a block's address is
1196forgotten but \cfunction{free()} is not called for it, the memory it
1197occupies cannot be reused until the program terminates. This is
1198called a \dfn{memory leak}. On the other hand, if a program calls
1199\cfunction{free()} for a block and then continues to use the block, it
1200creates a conflict with re-use of the block through another
1201\cfunction{malloc()} call. This is called \dfn{using freed memory}.
1202It has the same bad consequences as referencing uninitialized data ---
1203core dumps, wrong results, mysterious crashes.
1204
1205Common causes of memory leaks are unusual paths through the code. For
1206instance, a function may allocate a block of memory, do some
1207calculation, and then free the block again. Now a change in the
1208requirements for the function may add a test to the calculation that
1209detects an error condition and can return prematurely from the
1210function. It's easy to forget to free the allocated memory block when
1211taking this premature exit, especially when it is added later to the
1212code. Such leaks, once introduced, often go undetected for a long
1213time: the error exit is taken only in a small fraction of all calls,
1214and most modern machines have plenty of virtual memory, so the leak
1215only becomes apparent in a long-running process that uses the leaking
1216function frequently. Therefore, it's important to prevent leaks from
1217happening by having a coding convention or strategy that minimizes
1218this kind of errors.
1219
1220Since Python makes heavy use of \cfunction{malloc()} and
1221\cfunction{free()}, it needs a strategy to avoid memory leaks as well
1222as the use of freed memory. The chosen method is called
1223\dfn{reference counting}. The principle is simple: every object
1224contains a counter, which is incremented when a reference to the
1225object is stored somewhere, and which is decremented when a reference
1226to it is deleted. When the counter reaches zero, the last reference
1227to the object has been deleted and the object is freed.
1228
1229An alternative strategy is called \dfn{automatic garbage collection}.
1230(Sometimes, reference counting is also referred to as a garbage
1231collection strategy, hence my use of ``automatic'' to distinguish the
1232two.) The big advantage of automatic garbage collection is that the
1233user doesn't need to call \cfunction{free()} explicitly. (Another claimed
1234advantage is an improvement in speed or memory usage --- this is no
1235hard fact however.) The disadvantage is that for C, there is no
1236truly portable automatic garbage collector, while reference counting
1237can be implemented portably (as long as the functions \cfunction{malloc()}
1238and \cfunction{free()} are available --- which the C Standard guarantees).
1239Maybe some day a sufficiently portable automatic garbage collector
1240will be available for C. Until then, we'll have to live with
1241reference counts.
1242
Fred Drake024e6472001-12-07 17:30:40 +00001243While Python uses the traditional reference counting implementation,
1244it also offers a cycle detector that works to detect reference
1245cycles. This allows applications to not worry about creating direct
1246or indirect circular references; these are the weakness of garbage
1247collection implemented using only reference counting. Reference
1248cycles consist of objects which contain (possibly indirect) references
Tim Peters874c4f02001-12-07 17:51:41 +00001249to themselves, so that each object in the cycle has a reference count
Fred Drake024e6472001-12-07 17:30:40 +00001250which is non-zero. Typical reference counting implementations are not
Tim Peters874c4f02001-12-07 17:51:41 +00001251able to reclaim the memory belonging to any objects in a reference
Fred Drake024e6472001-12-07 17:30:40 +00001252cycle, or referenced from the objects in the cycle, even though there
1253are no further references to the cycle itself.
1254
1255The cycle detector is able to detect garbage cycles and can reclaim
1256them so long as there are no finalizers implemented in Python
1257(\method{__del__()} methods). When there are such finalizers, the
1258detector exposes the cycles through the \ulink{\module{gc}
Guido van Rossum44b3f762001-12-07 17:57:56 +00001259module}{../lib/module-gc.html} (specifically, the \code{garbage}
1260variable in that module). The \module{gc} module also exposes a way
1261to run the detector (the \function{collect()} function), as well as
Fred Drake024e6472001-12-07 17:30:40 +00001262configuration interfaces and the ability to disable the detector at
1263runtime. The cycle detector is considered an optional component;
Guido van Rossum44b3f762001-12-07 17:57:56 +00001264though it is included by default, it can be disabled at build time
Fred Drake024e6472001-12-07 17:30:40 +00001265using the \longprogramopt{without-cycle-gc} option to the
1266\program{configure} script on \UNIX{} platforms (including Mac OS X)
1267or by removing the definition of \code{WITH_CYCLE_GC} in the
1268\file{pyconfig.h} header on other platforms. If the cycle detector is
1269disabled in this way, the \module{gc} module will not be available.
1270
1271
Fred Drakecc8f44b2001-08-20 19:30:29 +00001272\subsection{Reference Counting in Python
1273 \label{refcountsInPython}}
1274
1275There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
1276which handle the incrementing and decrementing of the reference count.
1277\cfunction{Py_DECREF()} also frees the object when the count reaches zero.
1278For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
1279makes a call through a function pointer in the object's \dfn{type
1280object}. For this purpose (and others), every object also contains a
1281pointer to its type object.
1282
1283The big question now remains: when to use \code{Py_INCREF(x)} and
1284\code{Py_DECREF(x)}? Let's first introduce some terms. Nobody
1285``owns'' an object; however, you can \dfn{own a reference} to an
1286object. An object's reference count is now defined as the number of
1287owned references to it. The owner of a reference is responsible for
1288calling \cfunction{Py_DECREF()} when the reference is no longer
1289needed. Ownership of a reference can be transferred. There are three
1290ways to dispose of an owned reference: pass it on, store it, or call
1291\cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
1292creates a memory leak.
1293
1294It is also possible to \dfn{borrow}\footnote{The metaphor of
1295``borrowing'' a reference is not completely correct: the owner still
1296has a copy of the reference.} a reference to an object. The borrower
1297of a reference should not call \cfunction{Py_DECREF()}. The borrower must
1298not hold on to the object longer than the owner from which it was
1299borrowed. Using a borrowed reference after the owner has disposed of
1300it risks using freed memory and should be avoided
1301completely.\footnote{Checking that the reference count is at least 1
1302\strong{does not work} --- the reference count itself could be in
1303freed memory and may thus be reused for another object!}
1304
1305The advantage of borrowing over owning a reference is that you don't
1306need to take care of disposing of the reference on all possible paths
1307through the code --- in other words, with a borrowed reference you
1308don't run the risk of leaking when a premature exit is taken. The
1309disadvantage of borrowing over leaking is that there are some subtle
1310situations where in seemingly correct code a borrowed reference can be
1311used after the owner from which it was borrowed has in fact disposed
1312of it.
1313
1314A borrowed reference can be changed into an owned reference by calling
1315\cfunction{Py_INCREF()}. This does not affect the status of the owner from
1316which the reference was borrowed --- it creates a new owned reference,
1317and gives full owner responsibilities (the new owner must
1318dispose of the reference properly, as well as the previous owner).
1319
1320
1321\subsection{Ownership Rules
1322 \label{ownershipRules}}
1323
1324Whenever an object reference is passed into or out of a function, it
1325is part of the function's interface specification whether ownership is
1326transferred with the reference or not.
1327
1328Most functions that return a reference to an object pass on ownership
1329with the reference. In particular, all functions whose function it is
1330to create a new object, such as \cfunction{PyInt_FromLong()} and
Fred Drake92024d12001-11-29 07:16:19 +00001331\cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if
1332the object is not actually new, you still receive ownership of a new
1333reference to that object. For instance, \cfunction{PyInt_FromLong()}
1334maintains a cache of popular values and can return a reference to a
1335cached item.
Fred Drakecc8f44b2001-08-20 19:30:29 +00001336
1337Many functions that extract objects from other objects also transfer
1338ownership with the reference, for instance
1339\cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
1340however, since a few common routines are exceptions:
1341\cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
1342\cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
1343all return references that you borrow from the tuple, list or
1344dictionary.
1345
1346The function \cfunction{PyImport_AddModule()} also returns a borrowed
1347reference, even though it may actually create the object it returns:
1348this is possible because an owned reference to the object is stored in
1349\code{sys.modules}.
1350
1351When you pass an object reference into another function, in general,
1352the function borrows the reference from you --- if it needs to store
1353it, it will use \cfunction{Py_INCREF()} to become an independent
1354owner. There are exactly two important exceptions to this rule:
1355\cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
1356functions take over ownership of the item passed to them --- even if
1357they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
1358take over ownership --- they are ``normal.'')
1359
1360When a C function is called from Python, it borrows references to its
1361arguments from the caller. The caller owns a reference to the object,
1362so the borrowed reference's lifetime is guaranteed until the function
1363returns. Only when such a borrowed reference must be stored or passed
1364on, it must be turned into an owned reference by calling
1365\cfunction{Py_INCREF()}.
1366
1367The object reference returned from a C function that is called from
1368Python must be an owned reference --- ownership is tranferred from the
1369function to its caller.
1370
1371
1372\subsection{Thin Ice
1373 \label{thinIce}}
1374
1375There are a few situations where seemingly harmless use of a borrowed
1376reference can lead to problems. These all have to do with implicit
1377invocations of the interpreter, which can cause the owner of a
1378reference to dispose of it.
1379
1380The first and most important case to know about is using
1381\cfunction{Py_DECREF()} on an unrelated object while borrowing a
1382reference to a list item. For instance:
1383
1384\begin{verbatim}
1385bug(PyObject *list) {
1386 PyObject *item = PyList_GetItem(list, 0);
1387
1388 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1389 PyObject_Print(item, stdout, 0); /* BUG! */
1390}
1391\end{verbatim}
1392
1393This function first borrows a reference to \code{list[0]}, then
1394replaces \code{list[1]} with the value \code{0}, and finally prints
1395the borrowed reference. Looks harmless, right? But it's not!
1396
1397Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
1398owns references to all its items, so when item 1 is replaced, it has
1399to dispose of the original item 1. Now let's suppose the original
1400item 1 was an instance of a user-defined class, and let's further
1401suppose that the class defined a \method{__del__()} method. If this
1402class instance has a reference count of 1, disposing of it will call
1403its \method{__del__()} method.
1404
1405Since it is written in Python, the \method{__del__()} method can execute
1406arbitrary Python code. Could it perhaps do something to invalidate
1407the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
1408that the list passed into \cfunction{bug()} is accessible to the
1409\method{__del__()} method, it could execute a statement to the effect of
1410\samp{del list[0]}, and assuming this was the last reference to that
1411object, it would free the memory associated with it, thereby
1412invalidating \code{item}.
1413
1414The solution, once you know the source of the problem, is easy:
1415temporarily increment the reference count. The correct version of the
1416function reads:
1417
1418\begin{verbatim}
1419no_bug(PyObject *list) {
1420 PyObject *item = PyList_GetItem(list, 0);
1421
1422 Py_INCREF(item);
1423 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1424 PyObject_Print(item, stdout, 0);
1425 Py_DECREF(item);
1426}
1427\end{verbatim}
1428
1429This is a true story. An older version of Python contained variants
1430of this bug and someone spent a considerable amount of time in a C
1431debugger to figure out why his \method{__del__()} methods would fail...
1432
1433The second case of problems with a borrowed reference is a variant
1434involving threads. Normally, multiple threads in the Python
1435interpreter can't get in each other's way, because there is a global
1436lock protecting Python's entire object space. However, it is possible
1437to temporarily release this lock using the macro
1438\code{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
1439\code{Py_END_ALLOW_THREADS}. This is common around blocking I/O
1440calls, to let other threads use the processor while waiting for the I/O to
1441complete. Obviously, the following function has the same problem as
1442the previous one:
1443
1444\begin{verbatim}
1445bug(PyObject *list) {
1446 PyObject *item = PyList_GetItem(list, 0);
1447 Py_BEGIN_ALLOW_THREADS
1448 ...some blocking I/O call...
1449 Py_END_ALLOW_THREADS
1450 PyObject_Print(item, stdout, 0); /* BUG! */
1451}
1452\end{verbatim}
1453
1454
1455\subsection{NULL Pointers
1456 \label{nullPointers}}
1457
1458In general, functions that take object references as arguments do not
1459expect you to pass them \NULL{} pointers, and will dump core (or
1460cause later core dumps) if you do so. Functions that return object
1461references generally return \NULL{} only to indicate that an
1462exception occurred. The reason for not testing for \NULL{}
1463arguments is that functions often pass the objects they receive on to
Fred Drakec37b65e2001-11-28 07:26:15 +00001464other function --- if each function were to test for \NULL,
Fred Drakecc8f44b2001-08-20 19:30:29 +00001465there would be a lot of redundant tests and the code would run more
1466slowly.
1467
1468It is better to test for \NULL{} only at the ``source:'' when a
1469pointer that may be \NULL{} is received, for example, from
1470\cfunction{malloc()} or from a function that may raise an exception.
1471
1472The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
1473do not check for \NULL{} pointers --- however, their variants
1474\cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
1475
1476The macros for checking for a particular object type
1477(\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
1478again, there is much code that calls several of these in a row to test
1479an object against various different expected types, and this would
1480generate redundant tests. There are no variants with \NULL{}
1481checking.
1482
1483The C function calling mechanism guarantees that the argument list
1484passed to C functions (\code{args} in the examples) is never
1485\NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
1486These guarantees don't hold when you use the ``old'' style
1487calling convention --- this is still found in much existing code.}
1488
1489It is a severe error to ever let a \NULL{} pointer ``escape'' to
1490the Python user.
1491
1492% Frank Stajano:
1493% A pedagogically buggy example, along the lines of the previous listing,
1494% would be helpful here -- showing in more concrete terms what sort of
1495% actions could cause the problem. I can't very well imagine it from the
1496% description.
1497
1498
Fred Drakec37b65e2001-11-28 07:26:15 +00001499\section{Writing Extensions in \Cpp
Fred Drakecc8f44b2001-08-20 19:30:29 +00001500 \label{cplusplus}}
1501
Fred Drakec37b65e2001-11-28 07:26:15 +00001502It is possible to write extension modules in \Cpp. Some restrictions
Fred Drakecc8f44b2001-08-20 19:30:29 +00001503apply. If the main program (the Python interpreter) is compiled and
1504linked by the C compiler, global or static objects with constructors
1505cannot be used. This is not a problem if the main program is linked
1506by the \Cpp{} compiler. Functions that will be called by the
1507Python interpreter (in particular, module initalization functions)
1508have to be declared using \code{extern "C"}.
1509It is unnecessary to enclose the Python header files in
1510\code{extern "C" \{...\}} --- they use this form already if the symbol
1511\samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
1512symbol).
1513
1514
1515\section{Providing a C API for an Extension Module
1516 \label{using-cobjects}}
1517\sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
1518
1519Many extension modules just provide new functions and types to be
1520used from Python, but sometimes the code in an extension module can
1521be useful for other extension modules. For example, an extension
1522module could implement a type ``collection'' which works like lists
1523without order. Just like the standard Python list type has a C API
1524which permits extension modules to create and manipulate lists, this
1525new collection type should have a set of C functions for direct
1526manipulation from other extension modules.
1527
1528At first sight this seems easy: just write the functions (without
1529declaring them \keyword{static}, of course), provide an appropriate
1530header file, and document the C API. And in fact this would work if
1531all extension modules were always linked statically with the Python
1532interpreter. When modules are used as shared libraries, however, the
1533symbols defined in one module may not be visible to another module.
1534The details of visibility depend on the operating system; some systems
1535use one global namespace for the Python interpreter and all extension
1536modules (Windows, for example), whereas others require an explicit
1537list of imported symbols at module link time (AIX is one example), or
1538offer a choice of different strategies (most Unices). And even if
1539symbols are globally visible, the module whose functions one wishes to
1540call might not have been loaded yet!
1541
1542Portability therefore requires not to make any assumptions about
1543symbol visibility. This means that all symbols in extension modules
1544should be declared \keyword{static}, except for the module's
1545initialization function, in order to avoid name clashes with other
1546extension modules (as discussed in section~\ref{methodTable}). And it
1547means that symbols that \emph{should} be accessible from other
1548extension modules must be exported in a different way.
1549
1550Python provides a special mechanism to pass C-level information
1551(pointers) from one extension module to another one: CObjects.
1552A CObject is a Python data type which stores a pointer (\ctype{void
1553*}). CObjects can only be created and accessed via their C API, but
1554they can be passed around like any other Python object. In particular,
1555they can be assigned to a name in an extension module's namespace.
1556Other extension modules can then import this module, retrieve the
1557value of this name, and then retrieve the pointer from the CObject.
1558
1559There are many ways in which CObjects can be used to export the C API
1560of an extension module. Each name could get its own CObject, or all C
1561API pointers could be stored in an array whose address is published in
1562a CObject. And the various tasks of storing and retrieving the pointers
1563can be distributed in different ways between the module providing the
1564code and the client modules.
1565
1566The following example demonstrates an approach that puts most of the
1567burden on the writer of the exporting module, which is appropriate
1568for commonly used library modules. It stores all C API pointers
1569(just one in the example!) in an array of \ctype{void} pointers which
1570becomes the value of a CObject. The header file corresponding to
1571the module provides a macro that takes care of importing the module
1572and retrieving its C API pointers; client modules only have to call
1573this macro before accessing the C API.
1574
1575The exporting module is a modification of the \module{spam} module from
1576section~\ref{simpleExample}. The function \function{spam.system()}
1577does not call the C library function \cfunction{system()} directly,
1578but a function \cfunction{PySpam_System()}, which would of course do
1579something more complicated in reality (such as adding ``spam'' to
1580every command). This function \cfunction{PySpam_System()} is also
1581exported to other extension modules.
1582
1583The function \cfunction{PySpam_System()} is a plain C function,
1584declared \keyword{static} like everything else:
1585
1586\begin{verbatim}
1587static int
1588PySpam_System(command)
1589 char *command;
1590{
1591 return system(command);
1592}
1593\end{verbatim}
1594
1595The function \cfunction{spam_system()} is modified in a trivial way:
1596
1597\begin{verbatim}
1598static PyObject *
1599spam_system(self, args)
1600 PyObject *self;
1601 PyObject *args;
1602{
1603 char *command;
1604 int sts;
1605
1606 if (!PyArg_ParseTuple(args, "s", &command))
1607 return NULL;
1608 sts = PySpam_System(command);
1609 return Py_BuildValue("i", sts);
1610}
1611\end{verbatim}
1612
1613In the beginning of the module, right after the line
1614
1615\begin{verbatim}
1616#include "Python.h"
1617\end{verbatim}
1618
1619two more lines must be added:
1620
1621\begin{verbatim}
1622#define SPAM_MODULE
1623#include "spammodule.h"
1624\end{verbatim}
1625
1626The \code{\#define} is used to tell the header file that it is being
1627included in the exporting module, not a client module. Finally,
1628the module's initialization function must take care of initializing
1629the C API pointer array:
1630
1631\begin{verbatim}
1632void
Fred Drakeef6373a2001-11-17 06:50:42 +00001633initspam(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +00001634{
1635 PyObject *m;
1636 static void *PySpam_API[PySpam_API_pointers];
1637 PyObject *c_api_object;
1638
1639 m = Py_InitModule("spam", SpamMethods);
1640
1641 /* Initialize the C API pointer array */
1642 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1643
1644 /* Create a CObject containing the API pointer array's address */
1645 c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
1646
1647 if (c_api_object != NULL) {
1648 /* Create a name for this object in the module's namespace */
1649 PyObject *d = PyModule_GetDict(m);
1650
1651 PyDict_SetItemString(d, "_C_API", c_api_object);
1652 Py_DECREF(c_api_object);
1653 }
1654}
1655\end{verbatim}
1656
Fred Drakeef6373a2001-11-17 06:50:42 +00001657Note that \code{PySpam_API} is declared \keyword{static}; otherwise
1658the pointer array would disappear when \function{initspam()} terminates!
Fred Drakecc8f44b2001-08-20 19:30:29 +00001659
1660The bulk of the work is in the header file \file{spammodule.h},
1661which looks like this:
1662
1663\begin{verbatim}
1664#ifndef Py_SPAMMODULE_H
1665#define Py_SPAMMODULE_H
1666#ifdef __cplusplus
1667extern "C" {
1668#endif
1669
1670/* Header file for spammodule */
1671
1672/* C API functions */
1673#define PySpam_System_NUM 0
1674#define PySpam_System_RETURN int
1675#define PySpam_System_PROTO (char *command)
1676
1677/* Total number of C API pointers */
1678#define PySpam_API_pointers 1
1679
1680
1681#ifdef SPAM_MODULE
1682/* This section is used when compiling spammodule.c */
1683
1684static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1685
1686#else
1687/* This section is used in modules that use spammodule's API */
1688
1689static void **PySpam_API;
1690
1691#define PySpam_System \
1692 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1693
1694#define import_spam() \
1695{ \
1696 PyObject *module = PyImport_ImportModule("spam"); \
1697 if (module != NULL) { \
1698 PyObject *module_dict = PyModule_GetDict(module); \
1699 PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
1700 if (PyCObject_Check(c_api_object)) { \
1701 PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
1702 } \
1703 } \
1704}
1705
1706#endif
1707
1708#ifdef __cplusplus
1709}
1710#endif
1711
1712#endif /* !defined(Py_SPAMMODULE_H */
1713\end{verbatim}
1714
1715All that a client module must do in order to have access to the
1716function \cfunction{PySpam_System()} is to call the function (or
1717rather macro) \cfunction{import_spam()} in its initialization
1718function:
1719
1720\begin{verbatim}
1721void
Fred Drakeef6373a2001-11-17 06:50:42 +00001722initclient(void)
Fred Drakecc8f44b2001-08-20 19:30:29 +00001723{
1724 PyObject *m;
1725
1726 Py_InitModule("client", ClientMethods);
1727 import_spam();
1728}
1729\end{verbatim}
1730
1731The main disadvantage of this approach is that the file
1732\file{spammodule.h} is rather complicated. However, the
1733basic structure is the same for each function that is
1734exported, so it has to be learned only once.
1735
1736Finally it should be mentioned that CObjects offer additional
1737functionality, which is especially useful for memory allocation and
1738deallocation of the pointer stored in a CObject. The details
1739are described in the \citetitle[../api/api.html]{Python/C API
1740Reference Manual} in the section ``CObjects'' and in the
1741implementation of CObjects (files \file{Include/cobject.h} and
1742\file{Objects/cobject.c} in the Python source code distribution).