This commit was manufactured by cvs2svn to create tag 'r212'.
[python/dscho.git] / Doc / ext / ext.tex
blobbbe7efaf9b55211eafafd985078b26dfd88f5abd
1 \documentclass{manual}
3 % XXX PM explain how to add new types to Python
5 \title{Extending and Embedding the Python Interpreter}
7 \input{boilerplate}
9 % Tell \index to actually write the .idx file
10 \makeindex
12 \begin{document}
14 \maketitle
16 \ifhtml
17 \chapter*{Front Matter\label{front}}
18 \fi
20 \input{copyright}
23 \begin{abstract}
25 \noindent
26 Python is an interpreted, object-oriented programming language. This
27 document describes how to write modules in C or \Cpp{} to extend the
28 Python interpreter with new modules. Those modules can define new
29 functions but also new object types and their methods. The document
30 also describes how to embed the Python interpreter in another
31 application, for use as an extension language. Finally, it shows how
32 to compile and link extension modules so that they can be loaded
33 dynamically (at run time) into the interpreter, if the underlying
34 operating system supports this feature.
36 This document assumes basic knowledge about Python. For an informal
37 introduction to the language, see the
38 \citetitle[../tut/tut.html]{Python Tutorial}. The
39 \citetitle[../ref/ref.html]{Python Reference Manual} gives a more
40 formal definition of the language. The
41 \citetitle[../lib/lib.html]{Python Library Reference} documents the
42 existing object types, functions and modules (both built-in and
43 written in Python) that give the language its wide application range.
45 For a detailed description of the whole Python/C API, see the separate
46 \citetitle[../api/api.html]{Python/C API Reference Manual}.
48 \end{abstract}
50 \tableofcontents
53 \chapter{Extending Python with C or \Cpp{} \label{intro}}
56 It is quite easy to add new built-in modules to Python, if you know
57 how to program in C. Such \dfn{extension modules} can do two things
58 that can't be done directly in Python: they can implement new built-in
59 object types, and they can call C library functions and system calls.
61 To support extensions, the Python API (Application Programmers
62 Interface) defines a set of functions, macros and variables that
63 provide access to most aspects of the Python run-time system. The
64 Python API is incorporated in a C source file by including the header
65 \code{"Python.h"}.
67 The compilation of an extension module depends on its intended use as
68 well as on your system setup; details are given in later chapters.
71 \section{A Simple Example
72 \label{simpleExample}}
74 Let's create an extension module called \samp{spam} (the favorite food
75 of Monty Python fans...) and let's say we want to create a Python
76 interface to the C library function \cfunction{system()}.\footnote{An
77 interface for this function already exists in the standard module
78 \module{os} --- it was chosen as a simple and straightfoward example.}
79 This function takes a null-terminated character string as argument and
80 returns an integer. We want this function to be callable from Python
81 as follows:
83 \begin{verbatim}
84 >>> import spam
85 >>> status = spam.system("ls -l")
86 \end{verbatim}
88 Begin by creating a file \file{spammodule.c}. (Historically, if a
89 module is called \samp{spam}, the C file containing its implementation
90 is called \file{spammodule.c}; if the module name is very long, like
91 \samp{spammify}, the module name can be just \file{spammify.c}.)
93 The first line of our file can be:
95 \begin{verbatim}
96 #include <Python.h>
97 \end{verbatim}
99 which pulls in the Python API (you can add a comment describing the
100 purpose of the module and a copyright notice if you like).
102 All user-visible symbols defined by \code{"Python.h"} have a prefix of
103 \samp{Py} or \samp{PY}, except those defined in standard header files.
104 For convenience, and since they are used extensively by the Python
105 interpreter, \code{"Python.h"} includes a few standard header files:
106 \code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and
107 \code{<stdlib.h>}. If the latter header file does not exist on your
108 system, it declares the functions \cfunction{malloc()},
109 \cfunction{free()} and \cfunction{realloc()} directly.
111 The next thing we add to our module file is the C function that will
112 be called when the Python expression \samp{spam.system(\var{string})}
113 is evaluated (we'll see shortly how it ends up being called):
115 \begin{verbatim}
116 static PyObject *
117 spam_system(self, args)
118 PyObject *self;
119 PyObject *args;
121 char *command;
122 int sts;
124 if (!PyArg_ParseTuple(args, "s", &command))
125 return NULL;
126 sts = system(command);
127 return Py_BuildValue("i", sts);
129 \end{verbatim}
131 There is a straightforward translation from the argument list in
132 Python (e.g.\ the single expression \code{"ls -l"}) to the arguments
133 passed to the C function. The C function always has two arguments,
134 conventionally named \var{self} and \var{args}.
136 The \var{self} argument is only used when the C function implements a
137 built-in method, not a function. In the example, \var{self} will
138 always be a \NULL{} pointer, since we are defining a function, not a
139 method. (This is done so that the interpreter doesn't have to
140 understand two different types of C functions.)
142 The \var{args} argument will be a pointer to a Python tuple object
143 containing the arguments. Each item of the tuple corresponds to an
144 argument in the call's argument list. The arguments are Python
145 objects --- in order to do anything with them in our C function we have
146 to convert them to C values. The function \cfunction{PyArg_ParseTuple()}
147 in the Python API checks the argument types and converts them to C
148 values. It uses a template string to determine the required types of
149 the arguments as well as the types of the C variables into which to
150 store the converted values. More about this later.
152 \cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have
153 the right type and its components have been stored in the variables
154 whose addresses are passed. It returns false (zero) if an invalid
155 argument list was passed. In the latter case it also raises an
156 appropriate exception so the calling function can return
157 \NULL{} immediately (as we saw in the example).
160 \section{Intermezzo: Errors and Exceptions
161 \label{errors}}
163 An important convention throughout the Python interpreter is the
164 following: when a function fails, it should set an exception condition
165 and return an error value (usually a \NULL{} pointer). Exceptions
166 are stored in a static global variable inside the interpreter; if this
167 variable is \NULL{} no exception has occurred. A second global
168 variable stores the ``associated value'' of the exception (the second
169 argument to \keyword{raise}). A third variable contains the stack
170 traceback in case the error originated in Python code. These three
171 variables are the C equivalents of the Python variables
172 \code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see
173 the section on module \module{sys} in the
174 \citetitle[../lib/lib.html]{Python Library Reference}). It is
175 important to know about them to understand how errors are passed
176 around.
178 The Python API defines a number of functions to set various types of
179 exceptions.
181 The most common one is \cfunction{PyErr_SetString()}. Its arguments
182 are an exception object and a C string. The exception object is
183 usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The
184 C string indicates the cause of the error and is converted to a
185 Python string object and stored as the ``associated value'' of the
186 exception.
188 Another useful function is \cfunction{PyErr_SetFromErrno()}, which only
189 takes an exception argument and constructs the associated value by
190 inspection of the global variable \cdata{errno}. The most
191 general function is \cfunction{PyErr_SetObject()}, which takes two object
192 arguments, the exception and its associated value. You don't need to
193 \cfunction{Py_INCREF()} the objects passed to any of these functions.
195 You can test non-destructively whether an exception has been set with
196 \cfunction{PyErr_Occurred()}. This returns the current exception object,
197 or \NULL{} if no exception has occurred. You normally don't need
198 to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a
199 function call, since you should be able to tell from the return value.
201 When a function \var{f} that calls another function \var{g} detects
202 that the latter fails, \var{f} should itself return an error value
203 (e.g.\ \NULL{} or \code{-1}). It should \emph{not} call one of the
204 \cfunction{PyErr_*()} functions --- one has already been called by \var{g}.
205 \var{f}'s caller is then supposed to also return an error indication
206 to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()},
207 and so on --- the most detailed cause of the error was already
208 reported by the function that first detected it. Once the error
209 reaches the Python interpreter's main loop, this aborts the currently
210 executing Python code and tries to find an exception handler specified
211 by the Python programmer.
213 (There are situations where a module can actually give a more detailed
214 error message by calling another \cfunction{PyErr_*()} function, and in
215 such cases it is fine to do so. As a general rule, however, this is
216 not necessary, and can cause information about the cause of the error
217 to be lost: most operations can fail for a variety of reasons.)
219 To ignore an exception set by a function call that failed, the exception
220 condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}.
221 The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't
222 want to pass the error on to the interpreter but wants to handle it
223 completely by itself (e.g.\ by trying something else or pretending
224 nothing happened).
226 Every failing \cfunction{malloc()} call must be turned into an
227 exception --- the direct caller of \cfunction{malloc()} (or
228 \cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and
229 return a failure indicator itself. All the object-creating functions
230 (for example, \cfunction{PyInt_FromLong()}) already do this, so this
231 note is only relevant to those who call \cfunction{malloc()} directly.
233 Also note that, with the important exception of
234 \cfunction{PyArg_ParseTuple()} and friends, functions that return an
235 integer status usually return a positive value or zero for success and
236 \code{-1} for failure, like \UNIX{} system calls.
238 Finally, be careful to clean up garbage (by making
239 \cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects
240 you have already created) when you return an error indicator!
242 The choice of which exception to raise is entirely yours. There are
243 predeclared C objects corresponding to all built-in Python exceptions,
244 e.g.\ \cdata{PyExc_ZeroDivisionError}, which you can use directly. Of
245 course, you should choose exceptions wisely --- don't use
246 \cdata{PyExc_TypeError} to mean that a file couldn't be opened (that
247 should probably be \cdata{PyExc_IOError}). If something's wrong with
248 the argument list, the \cfunction{PyArg_ParseTuple()} function usually
249 raises \cdata{PyExc_TypeError}. If you have an argument whose value
250 must be in a particular range or must satisfy other conditions,
251 \cdata{PyExc_ValueError} is appropriate.
253 You can also define a new exception that is unique to your module.
254 For this, you usually declare a static object variable at the
255 beginning of your file, e.g.
257 \begin{verbatim}
258 static PyObject *SpamError;
259 \end{verbatim}
261 and initialize it in your module's initialization function
262 (\cfunction{initspam()}) with an exception object, e.g.\ (leaving out
263 the error checking for now):
265 \begin{verbatim}
266 void
267 initspam()
269 PyObject *m, *d;
271 m = Py_InitModule("spam", SpamMethods);
272 d = PyModule_GetDict(m);
273 SpamError = PyErr_NewException("spam.error", NULL, NULL);
274 PyDict_SetItemString(d, "error", SpamError);
276 \end{verbatim}
278 Note that the Python name for the exception object is
279 \exception{spam.error}. The \cfunction{PyErr_NewException()} function
280 may create a class with the base class being \exception{Exception}
281 (unless another class is passed in instead of \NULL), described in the
282 \citetitle[../lib/lib.html]{Python Library Reference} under ``Built-in
283 Exceptions.''
285 Note also that the \cdata{SpamError} variable retains a reference to
286 the newly created exception class; this is intentional! Since the
287 exception could be removed from the module by external code, an owned
288 reference to the class is needed to ensure that it will not be
289 discarded, causing \cdata{SpamError} to become a dangling pointer.
290 Should it become a dangling pointer, C code which raises the exception
291 could cause a core dump or other unintended side effects.
294 \section{Back to the Example
295 \label{backToExample}}
297 Going back to our example function, you should now be able to
298 understand this statement:
300 \begin{verbatim}
301 if (!PyArg_ParseTuple(args, "s", &command))
302 return NULL;
303 \end{verbatim}
305 It returns \NULL{} (the error indicator for functions returning
306 object pointers) if an error is detected in the argument list, relying
307 on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the
308 string value of the argument has been copied to the local variable
309 \cdata{command}. This is a pointer assignment and you are not supposed
310 to modify the string to which it points (so in Standard C, the variable
311 \cdata{command} should properly be declared as \samp{const char
312 *command}).
314 The next statement is a call to the \UNIX{} function
315 \cfunction{system()}, passing it the string we just got from
316 \cfunction{PyArg_ParseTuple()}:
318 \begin{verbatim}
319 sts = system(command);
320 \end{verbatim}
322 Our \function{spam.system()} function must return the value of
323 \cdata{sts} as a Python object. This is done using the function
324 \cfunction{Py_BuildValue()}, which is something like the inverse of
325 \cfunction{PyArg_ParseTuple()}: it takes a format string and an
326 arbitrary number of C values, and returns a new Python object.
327 More info on \cfunction{Py_BuildValue()} is given later.
329 \begin{verbatim}
330 return Py_BuildValue("i", sts);
331 \end{verbatim}
333 In this case, it will return an integer object. (Yes, even integers
334 are objects on the heap in Python!)
336 If you have a C function that returns no useful argument (a function
337 returning \ctype{void}), the corresponding Python function must return
338 \code{None}. You need this idiom to do so:
340 \begin{verbatim}
341 Py_INCREF(Py_None);
342 return Py_None;
343 \end{verbatim}
345 \cdata{Py_None} is the C name for the special Python object
346 \code{None}. It is a genuine Python object rather than a \NULL{}
347 pointer, which means ``error'' in most contexts, as we have seen.
350 \section{The Module's Method Table and Initialization Function
351 \label{methodTable}}
353 I promised to show how \cfunction{spam_system()} is called from Python
354 programs. First, we need to list its name and address in a ``method
355 table'':
357 \begin{verbatim}
358 static PyMethodDef SpamMethods[] = {
360 {"system", spam_system, METH_VARARGS},
362 {NULL, NULL} /* Sentinel */
364 \end{verbatim}
366 Note the third entry (\samp{METH_VARARGS}). This is a flag telling
367 the interpreter the calling convention to be used for the C
368 function. It should normally always be \samp{METH_VARARGS} or
369 \samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an
370 obsolete variant of \cfunction{PyArg_ParseTuple()} is used.
372 When using only \samp{METH_VARARGS}, the function should expect
373 the Python-level parameters to be passed in as a tuple acceptable for
374 parsing via \cfunction{PyArg_ParseTuple()}; more information on this
375 function is provided below.
377 The \constant{METH_KEYWORDS} bit may be set in the third field if
378 keyword arguments should be passed to the function. In this case, the
379 C function should accept a third \samp{PyObject *} parameter which
380 will be a dictionary of keywords. Use
381 \cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to
382 such a function.
384 The method table must be passed to the interpreter in the module's
385 initialization function. The initialization function must be named
386 \cfunction{init\var{name}()}, where \var{name} is the name of the
387 module, and should be the only non-\keyword{static} item defined in
388 the module file:
390 \begin{verbatim}
391 void
392 initspam()
394 (void) Py_InitModule("spam", SpamMethods);
396 \end{verbatim}
398 Note that for \Cpp, this method must be declared \code{extern "C"}.
400 When the Python program imports module \module{spam} for the first
401 time, \cfunction{initspam()} is called. (See below for comments about
402 embedding Python.) It calls
403 \cfunction{Py_InitModule()}, which creates a ``module object'' (which
404 is inserted in the dictionary \code{sys.modules} under the key
405 \code{"spam"}), and inserts built-in function objects into the newly
406 created module based upon the table (an array of \ctype{PyMethodDef}
407 structures) that was passed as its second argument.
408 \cfunction{Py_InitModule()} returns a pointer to the module object
409 that it creates (which is unused here). It aborts with a fatal error
410 if the module could not be initialized satisfactorily, so the caller
411 doesn't need to check for errors.
413 When embedding Python, the \cfunction{initspam()} function is not
414 called automatically unless there's an entry in the
415 \cdata{_PyImport_Inittab} table. The easiest way to handle this is to
416 statically initialize your statically-linked modules by directly
417 calling \cfunction{initspam()} after the call to
418 \cfunction{Py_Initialize()} or \cfunction{PyMac_Initialize()}:
420 \begin{verbatim}
421 int main(int argc, char **argv)
423 /* Pass argv[0] to the Python interpreter */
424 Py_SetProgramName(argv[0]);
426 /* Initialize the Python interpreter. Required. */
427 Py_Initialize();
429 /* Add a static module */
430 initspam();
431 \end{verbatim}
433 An example may be found in the file \file{Demo/embed/demo.c} in the
434 Python source distribution.
436 \strong{Note:} Removing entries from \code{sys.modules} or importing
437 compiled modules into multiple interpreters within a process (or
438 following a \cfunction{fork()} without an intervening
439 \cfunction{exec()}) can create problems for some extension modules.
440 Extension module authors should exercise caution when initializing
441 internal data structures.
442 Note also that the \function{reload()} function can be used with
443 extension modules, and will call the module initialization function
444 (\cfunction{initspam()} in the example), but will not load the module
445 again if it was loaded from a dynamically loadable object file
446 (\file{.so} on \UNIX, \file{.dll} on Windows).
448 A more substantial example module is included in the Python source
449 distribution as \file{Modules/xxmodule.c}. This file may be used as a
450 template or simply read as an example. The \program{modulator.py}
451 script included in the source distribution or Windows install provides
452 a simple graphical user interface for declaring the functions and
453 objects which a module should implement, and can generate a template
454 which can be filled in. The script lives in the
455 \file{Tools/modulator/} directory; see the \file{README} file there
456 for more information.
459 \section{Compilation and Linkage
460 \label{compilation}}
462 There are two more things to do before you can use your new extension:
463 compiling and linking it with the Python system. If you use dynamic
464 loading, the details depend on the style of dynamic loading your
465 system uses; see the chapters about building extension modules on
466 \UNIX{} (chapter \ref{building-on-unix}) and Windows (chapter
467 \ref{building-on-windows}) for more information about this.
468 % XXX Add information about MacOS
470 If you can't use dynamic loading, or if you want to make your module a
471 permanent part of the Python interpreter, you will have to change the
472 configuration setup and rebuild the interpreter. Luckily, this is
473 very simple: just place your file (\file{spammodule.c} for example) in
474 the \file{Modules/} directory of an unpacked source distribution, add
475 a line to the file \file{Modules/Setup.local} describing your file:
477 \begin{verbatim}
478 spam spammodule.o
479 \end{verbatim}
481 and rebuild the interpreter by running \program{make} in the toplevel
482 directory. You can also run \program{make} in the \file{Modules/}
483 subdirectory, but then you must first rebuild \file{Makefile}
484 there by running `\program{make} Makefile'. (This is necessary each
485 time you change the \file{Setup} file.)
487 If your module requires additional libraries to link with, these can
488 be listed on the line in the configuration file as well, for instance:
490 \begin{verbatim}
491 spam spammodule.o -lX11
492 \end{verbatim}
494 \section{Calling Python Functions from C
495 \label{callingPython}}
497 So far we have concentrated on making C functions callable from
498 Python. The reverse is also useful: calling Python functions from C.
499 This is especially the case for libraries that support so-called
500 ``callback'' functions. If a C interface makes use of callbacks, the
501 equivalent Python often needs to provide a callback mechanism to the
502 Python programmer; the implementation will require calling the Python
503 callback functions from a C callback. Other uses are also imaginable.
505 Fortunately, the Python interpreter is easily called recursively, and
506 there is a standard interface to call a Python function. (I won't
507 dwell on how to call the Python parser with a particular string as
508 input --- if you're interested, have a look at the implementation of
509 the \programopt{-c} command line option in \file{Python/pythonmain.c}
510 from the Python source code.)
512 Calling a Python function is easy. First, the Python program must
513 somehow pass you the Python function object. You should provide a
514 function (or some other interface) to do this. When this function is
515 called, save a pointer to the Python function object (be careful to
516 \cfunction{Py_INCREF()} it!) in a global variable --- or wherever you
517 see fit. For example, the following function might be part of a module
518 definition:
520 \begin{verbatim}
521 static PyObject *my_callback = NULL;
523 static PyObject *
524 my_set_callback(dummy, args)
525 PyObject *dummy, *args;
527 PyObject *result = NULL;
528 PyObject *temp;
530 if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
531 if (!PyCallable_Check(temp)) {
532 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
533 return NULL;
535 Py_XINCREF(temp); /* Add a reference to new callback */
536 Py_XDECREF(my_callback); /* Dispose of previous callback */
537 my_callback = temp; /* Remember new callback */
538 /* Boilerplate to return "None" */
539 Py_INCREF(Py_None);
540 result = Py_None;
542 return result;
544 \end{verbatim}
546 This function must be registered with the interpreter using the
547 \constant{METH_VARARGS} flag; this is described in section
548 \ref{methodTable}, ``The Module's Method Table and Initialization
549 Function.'' The \cfunction{PyArg_ParseTuple()} function and its
550 arguments are documented in section \ref{parseTuple}, ``Format Strings
551 for \cfunction{PyArg_ParseTuple()}.''
553 The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()}
554 increment/decrement the reference count of an object and are safe in
555 the presence of \NULL{} pointers (but note that \var{temp} will not be
556 \NULL{} in this context). More info on them in section
557 \ref{refcounts}, ``Reference Counts.''
559 Later, when it is time to call the function, you call the C function
560 \cfunction{PyEval_CallObject()}. This function has two arguments, both
561 pointers to arbitrary Python objects: the Python function, and the
562 argument list. The argument list must always be a tuple object, whose
563 length is the number of arguments. To call the Python function with
564 no arguments, pass an empty tuple; to call it with one argument, pass
565 a singleton tuple. \cfunction{Py_BuildValue()} returns a tuple when its
566 format string consists of zero or more format codes between
567 parentheses. For example:
569 \begin{verbatim}
570 int arg;
571 PyObject *arglist;
572 PyObject *result;
574 arg = 123;
576 /* Time to call the callback */
577 arglist = Py_BuildValue("(i)", arg);
578 result = PyEval_CallObject(my_callback, arglist);
579 Py_DECREF(arglist);
580 \end{verbatim}
582 \cfunction{PyEval_CallObject()} returns a Python object pointer: this is
583 the return value of the Python function. \cfunction{PyEval_CallObject()} is
584 ``reference-count-neutral'' with respect to its arguments. In the
585 example a new tuple was created to serve as the argument list, which
586 is \cfunction{Py_DECREF()}-ed immediately after the call.
588 The return value of \cfunction{PyEval_CallObject()} is ``new'': either it
589 is a brand new object, or it is an existing object whose reference
590 count has been incremented. So, unless you want to save it in a
591 global variable, you should somehow \cfunction{Py_DECREF()} the result,
592 even (especially!) if you are not interested in its value.
594 Before you do this, however, it is important to check that the return
595 value isn't \NULL{}. If it is, the Python function terminated by
596 raising an exception. If the C code that called
597 \cfunction{PyEval_CallObject()} is called from Python, it should now
598 return an error indication to its Python caller, so the interpreter
599 can print a stack trace, or the calling Python code can handle the
600 exception. If this is not possible or desirable, the exception should
601 be cleared by calling \cfunction{PyErr_Clear()}. For example:
603 \begin{verbatim}
604 if (result == NULL)
605 return NULL; /* Pass error back */
606 ...use result...
607 Py_DECREF(result);
608 \end{verbatim}
610 Depending on the desired interface to the Python callback function,
611 you may also have to provide an argument list to
612 \cfunction{PyEval_CallObject()}. In some cases the argument list is
613 also provided by the Python program, through the same interface that
614 specified the callback function. It can then be saved and used in the
615 same manner as the function object. In other cases, you may have to
616 construct a new tuple to pass as the argument list. The simplest way
617 to do this is to call \cfunction{Py_BuildValue()}. For example, if
618 you want to pass an integral event code, you might use the following
619 code:
621 \begin{verbatim}
622 PyObject *arglist;
624 arglist = Py_BuildValue("(l)", eventcode);
625 result = PyEval_CallObject(my_callback, arglist);
626 Py_DECREF(arglist);
627 if (result == NULL)
628 return NULL; /* Pass error back */
629 /* Here maybe use the result */
630 Py_DECREF(result);
631 \end{verbatim}
633 Note the placement of \samp{Py_DECREF(arglist)} immediately after the
634 call, before the error check! Also note that strictly spoken this
635 code is not complete: \cfunction{Py_BuildValue()} may run out of
636 memory, and this should be checked.
639 \section{Extracting Parameters in Extension Functions
640 \label{parseTuple}}
642 The \cfunction{PyArg_ParseTuple()} function is declared as follows:
644 \begin{verbatim}
645 int PyArg_ParseTuple(PyObject *arg, char *format, ...);
646 \end{verbatim}
648 The \var{arg} argument must be a tuple object containing an argument
649 list passed from Python to a C function. The \var{format} argument
650 must be a format string, whose syntax is explained below. The
651 remaining arguments must be addresses of variables whose type is
652 determined by the format string. For the conversion to succeed, the
653 \var{arg} object must match the format and the format must be
654 exhausted.
656 Note that while \cfunction{PyArg_ParseTuple()} checks that the Python
657 arguments have the required types, it cannot check the validity of the
658 addresses of C variables passed to the call: if you make mistakes
659 there, your code will probably crash or at least overwrite random bits
660 in memory. So be careful!
662 A format string consists of zero or more ``format units''. A format
663 unit describes one Python object; it is usually a single character or
664 a parenthesized sequence of format units. With a few exceptions, a
665 format unit that is not a parenthesized sequence normally corresponds
666 to a single address argument to \cfunction{PyArg_ParseTuple()}. In the
667 following description, the quoted form is the format unit; the entry
668 in (round) parentheses is the Python object type that matches the
669 format unit; and the entry in [square] brackets is the type of the C
670 variable(s) whose address should be passed. (Use the \samp{\&}
671 operator to pass a variable's address.)
673 Note that any Python object references which are provided to the
674 caller are \emph{borrowed} references; do not decrement their
675 reference count!
677 \begin{description}
679 \item[\samp{s} (string or Unicode object) {[char *]}]
680 Convert a Python string or Unicode object to a C pointer to a
681 character string. You must not provide storage for the string
682 itself; a pointer to an existing string is stored into the character
683 pointer variable whose address you pass. The C string is
684 null-terminated. The Python string must not contain embedded null
685 bytes; if it does, a \exception{TypeError} exception is raised.
686 Unicode objects are converted to C strings using the default
687 encoding. If this conversion fails, an \exception{UnicodeError} is
688 raised.
690 \item[\samp{s\#} (string, Unicode or any read buffer compatible object)
691 {[char *, int]}]
692 This variant on \samp{s} stores into two C variables, the first one a
693 pointer to a character string, the second one its length. In this
694 case the Python string may contain embedded null bytes. Unicode
695 objects pass back a pointer to the default encoded string version of the
696 object if such a conversion is possible. All other read buffer
697 compatible objects pass back a reference to the raw internal data
698 representation.
700 \item[\samp{z} (string or \code{None}) {[char *]}]
701 Like \samp{s}, but the Python object may also be \code{None}, in which
702 case the C pointer is set to \NULL{}.
704 \item[\samp{z\#} (string or \code{None} or any read buffer compatible object)
705 {[char *, int]}]
706 This is to \samp{s\#} as \samp{z} is to \samp{s}.
708 \item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
709 Convert a Python Unicode object to a C pointer to a null-terminated
710 buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need
711 to provide storage for the Unicode data buffer; a pointer to the
712 existing Unicode data is stored into the Py_UNICODE pointer variable whose
713 address you pass.
715 \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
716 This variant on \samp{u} stores into two C variables, the first one
717 a pointer to a Unicode data buffer, the second one its length.
719 \item[\samp{es} (string, Unicode object or character buffer compatible
720 object) {[const char *encoding, char **buffer]}]
721 This variant on \samp{s} is used for encoding Unicode and objects
722 convertible to Unicode into a character buffer. It only works for
723 encoded data without embedded \NULL{} bytes.
725 The variant reads one C variable and stores into two C variables, the
726 first one a pointer to an encoding name string (\var{encoding}), and the
727 second a pointer to a pointer to a character buffer (\var{**buffer},
728 the buffer used for storing the encoded data).
730 The encoding name must map to a registered codec. If set to \NULL{},
731 the default encoding is used.
733 \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
734 size using \cfunction{PyMem_NEW()}, copy the encoded data into this
735 buffer and adjust \var{*buffer} to reference the newly allocated
736 storage. The caller is responsible for calling
737 \cfunction{PyMem_Free()} to free the allocated buffer after usage.
739 \item[\samp{es\#} (string, Unicode object or character buffer compatible
740 object) {[const char *encoding, char **buffer, int *buffer_length]}]
741 This variant on \samp{s\#} is used for encoding Unicode and objects
742 convertible to Unicode into a character buffer. It reads one C
743 variable and stores into three C variables, the first one a pointer to
744 an encoding name string (\var{encoding}), the second a pointer to a
745 pointer to a character buffer (\var{**buffer}, the buffer used for
746 storing the encoded data) and the third one a pointer to an integer
747 (\var{*buffer_length}, the buffer length).
749 The encoding name must map to a registered codec. If set to \NULL{},
750 the default encoding is used.
752 There are two modes of operation:
754 If \var{*buffer} points a \NULL{} pointer,
755 \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
756 size using \cfunction{PyMem_NEW()}, copy the encoded data into this
757 buffer and adjust \var{*buffer} to reference the newly allocated
758 storage. The caller is responsible for calling
759 \cfunction{PyMem_Free()} to free the allocated buffer after usage.
761 If \var{*buffer} points to a non-\NULL{} pointer (an already allocated
762 buffer), \cfunction{PyArg_ParseTuple()} will use this location as
763 buffer and interpret \var{*buffer_length} as buffer size. It will then
764 copy the encoded data into the buffer and 0-terminate it. Buffer
765 overflow is signalled with an exception.
767 In both cases, \var{*buffer_length} is set to the length of the
768 encoded data without the trailing 0-byte.
770 \item[\samp{b} (integer) {[char]}]
771 Convert a Python integer to a tiny int, stored in a C \ctype{char}.
773 \item[\samp{h} (integer) {[short int]}]
774 Convert a Python integer to a C \ctype{short int}.
776 \item[\samp{i} (integer) {[int]}]
777 Convert a Python integer to a plain C \ctype{int}.
779 \item[\samp{l} (integer) {[long int]}]
780 Convert a Python integer to a C \ctype{long int}.
782 \item[\samp{c} (string of length 1) {[char]}]
783 Convert a Python character, represented as a string of length 1, to a
784 C \ctype{char}.
786 \item[\samp{f} (float) {[float]}]
787 Convert a Python floating point number to a C \ctype{float}.
789 \item[\samp{d} (float) {[double]}]
790 Convert a Python floating point number to a C \ctype{double}.
792 \item[\samp{D} (complex) {[Py_complex]}]
793 Convert a Python complex number to a C \ctype{Py_complex} structure.
795 \item[\samp{O} (object) {[PyObject *]}]
796 Store a Python object (without any conversion) in a C object pointer.
797 The C program thus receives the actual object that was passed. The
798 object's reference count is not increased. The pointer stored is not
799 \NULL{}.
801 \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
802 Store a Python object in a C object pointer. This is similar to
803 \samp{O}, but takes two C arguments: the first is the address of a
804 Python type object, the second is the address of the C variable (of
805 type \ctype{PyObject *}) into which the object pointer is stored.
806 If the Python object does not have the required type,
807 \exception{TypeError} is raised.
809 \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
810 Convert a Python object to a C variable through a \var{converter}
811 function. This takes two arguments: the first is a function, the
812 second is the address of a C variable (of arbitrary type), converted
813 to \ctype{void *}. The \var{converter} function in turn is called as
814 follows:
816 \var{status}\code{ = }\var{converter}\code{(}\var{object}, \var{address}\code{);}
818 where \var{object} is the Python object to be converted and
819 \var{address} is the \ctype{void *} argument that was passed to
820 \cfunction{PyArg_ConvertTuple()}. The returned \var{status} should be
821 \code{1} for a successful conversion and \code{0} if the conversion
822 has failed. When the conversion fails, the \var{converter} function
823 should raise an exception.
825 \item[\samp{S} (string) {[PyStringObject *]}]
826 Like \samp{O} but requires that the Python object is a string object.
827 Raises \exception{TypeError} if the object is not a string object.
828 The C variable may also be declared as \ctype{PyObject *}.
830 \item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
831 Like \samp{O} but requires that the Python object is a Unicode object.
832 Raises \exception{TypeError} if the object is not a Unicode object.
833 The C variable may also be declared as \ctype{PyObject *}.
835 \item[\samp{t\#} (read-only character buffer) {[char *, int]}]
836 Like \samp{s\#}, but accepts any object which implements the read-only
837 buffer interface. The \ctype{char *} variable is set to point to the
838 first byte of the buffer, and the \ctype{int} is set to the length of
839 the buffer. Only single-segment buffer objects are accepted;
840 \exception{TypeError} is raised for all others.
842 \item[\samp{w} (read-write character buffer) {[char *]}]
843 Similar to \samp{s}, but accepts any object which implements the
844 read-write buffer interface. The caller must determine the length of
845 the buffer by other means, or use \samp{w\#} instead. Only
846 single-segment buffer objects are accepted; \exception{TypeError} is
847 raised for all others.
849 \item[\samp{w\#} (read-write character buffer) {[char *, int]}]
850 Like \samp{s\#}, but accepts any object which implements the
851 read-write buffer interface. The \ctype{char *} variable is set to
852 point to the first byte of the buffer, and the \ctype{int} is set to
853 the length of the buffer. Only single-segment buffer objects are
854 accepted; \exception{TypeError} is raised for all others.
856 \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
857 The object must be a Python sequence whose length is the number of
858 format units in \var{items}. The C arguments must correspond to the
859 individual format units in \var{items}. Format units for sequences
860 may be nested.
862 \strong{Note:} Prior to Python version 1.5.2, this format specifier
863 only accepted a tuple containing the individual parameters, not an
864 arbitrary sequence. Code which previously caused
865 \exception{TypeError} to be raised here may now proceed without an
866 exception. This is not expected to be a problem for existing code.
868 \end{description}
870 It is possible to pass Python long integers where integers are
871 requested; however no proper range checking is done --- the most
872 significant bits are silently truncated when the receiving field is
873 too small to receive the value (actually, the semantics are inherited
874 from downcasts in C --- your mileage may vary).
876 A few other characters have a meaning in a format string. These may
877 not occur inside nested parentheses. They are:
879 \begin{description}
881 \item[\samp{|}]
882 Indicates that the remaining arguments in the Python argument list are
883 optional. The C variables corresponding to optional arguments should
884 be initialized to their default value --- when an optional argument is
885 not specified, \cfunction{PyArg_ParseTuple()} does not touch the contents
886 of the corresponding C variable(s).
888 \item[\samp{:}]
889 The list of format units ends here; the string after the colon is used
890 as the function name in error messages (the ``associated value'' of
891 the exception that \cfunction{PyArg_ParseTuple()} raises).
893 \item[\samp{;}]
894 The list of format units ends here; the string after the semicolon is
895 used as the error message \emph{instead} of the default error message.
896 Clearly, \samp{:} and \samp{;} mutually exclude each other.
898 \end{description}
900 Some example calls:
902 \begin{verbatim}
903 int ok;
904 int i, j;
905 long k, l;
906 char *s;
907 int size;
909 ok = PyArg_ParseTuple(args, ""); /* No arguments */
910 /* Python call: f() */
911 \end{verbatim}
913 \begin{verbatim}
914 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
915 /* Possible Python call: f('whoops!') */
916 \end{verbatim}
918 \begin{verbatim}
919 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
920 /* Possible Python call: f(1, 2, 'three') */
921 \end{verbatim}
923 \begin{verbatim}
924 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
925 /* A pair of ints and a string, whose size is also returned */
926 /* Possible Python call: f((1, 2), 'three') */
927 \end{verbatim}
929 \begin{verbatim}
931 char *file;
932 char *mode = "r";
933 int bufsize = 0;
934 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
935 /* A string, and optionally another string and an integer */
936 /* Possible Python calls:
937 f('spam')
938 f('spam', 'w')
939 f('spam', 'wb', 100000) */
941 \end{verbatim}
943 \begin{verbatim}
945 int left, top, right, bottom, h, v;
946 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
947 &left, &top, &right, &bottom, &h, &v);
948 /* A rectangle and a point */
949 /* Possible Python call:
950 f(((0, 0), (400, 300)), (10, 10)) */
952 \end{verbatim}
954 \begin{verbatim}
956 Py_complex c;
957 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
958 /* a complex, also providing a function name for errors */
959 /* Possible Python call: myfunction(1+2j) */
961 \end{verbatim}
964 \section{Keyword Parameters for Extension Functions
965 \label{parseTupleAndKeywords}}
967 The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
968 follows:
970 \begin{verbatim}
971 int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
972 char *format, char **kwlist, ...);
973 \end{verbatim}
975 The \var{arg} and \var{format} parameters are identical to those of the
976 \cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
977 is the dictionary of keywords received as the third parameter from the
978 Python runtime. The \var{kwlist} parameter is a \NULL{}-terminated
979 list of strings which identify the parameters; the names are matched
980 with the type information from \var{format} from left to right.
982 \strong{Note:} Nested tuples cannot be parsed when using keyword
983 arguments! Keyword parameters passed in which are not present in the
984 \var{kwlist} will cause \exception{TypeError} to be raised.
986 Here is an example module which uses keywords, based on an example by
987 Geoff Philbrick (\email{philbrick@hks.com}):%
988 \index{Philbrick, Geoff}
990 \begin{verbatim}
991 #include <stdio.h>
992 #include "Python.h"
994 static PyObject *
995 keywdarg_parrot(self, args, keywds)
996 PyObject *self;
997 PyObject *args;
998 PyObject *keywds;
1000 int voltage;
1001 char *state = "a stiff";
1002 char *action = "voom";
1003 char *type = "Norwegian Blue";
1005 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
1007 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
1008 &voltage, &state, &action, &type))
1009 return NULL;
1011 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
1012 action, voltage);
1013 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
1015 Py_INCREF(Py_None);
1017 return Py_None;
1020 static PyMethodDef keywdarg_methods[] = {
1021 /* The cast of the function is necessary since PyCFunction values
1022 * only take two PyObject* parameters, and keywdarg_parrot() takes
1023 * three.
1025 {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS},
1026 {NULL, NULL} /* sentinel */
1029 void
1030 initkeywdarg()
1032 /* Create the module and add the functions */
1033 Py_InitModule("keywdarg", keywdarg_methods);
1035 \end{verbatim}
1038 \section{Building Arbitrary Values
1039 \label{buildValue}}
1041 This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
1042 declared as follows:
1044 \begin{verbatim}
1045 PyObject *Py_BuildValue(char *format, ...);
1046 \end{verbatim}
1048 It recognizes a set of format units similar to the ones recognized by
1049 \cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
1050 function, not output) must not be pointers, just values. It returns a
1051 new Python object, suitable for returning from a C function called
1052 from Python.
1054 One difference with \cfunction{PyArg_ParseTuple()}: while the latter
1055 requires its first argument to be a tuple (since Python argument lists
1056 are always represented as tuples internally),
1057 \cfunction{Py_BuildValue()} does not always build a tuple. It builds
1058 a tuple only if its format string contains two or more format units.
1059 If the format string is empty, it returns \code{None}; if it contains
1060 exactly one format unit, it returns whatever object is described by
1061 that format unit. To force it to return a tuple of size 0 or one,
1062 parenthesize the format string.
1064 When memory buffers are passed as parameters to supply data to build
1065 objects, as for the \samp{s} and \samp{s\#} formats, the required data
1066 is copied. Buffers provided by the caller are never referenced by the
1067 objects created by \cfunction{Py_BuildValue()}. In other words, if
1068 your code invokes \cfunction{malloc()} and passes the allocated memory
1069 to \cfunction{Py_BuildValue()}, your code is responsible for
1070 calling \cfunction{free()} for that memory once
1071 \cfunction{Py_BuildValue()} returns.
1073 In the following description, the quoted form is the format unit; the
1074 entry in (round) parentheses is the Python object type that the format
1075 unit will return; and the entry in [square] brackets is the type of
1076 the C value(s) to be passed.
1078 The characters space, tab, colon and comma are ignored in format
1079 strings (but not within format units such as \samp{s\#}). This can be
1080 used to make long format strings a tad more readable.
1082 \begin{description}
1084 \item[\samp{s} (string) {[char *]}]
1085 Convert a null-terminated C string to a Python object. If the C
1086 string pointer is \NULL{}, \code{None} is used.
1088 \item[\samp{s\#} (string) {[char *, int]}]
1089 Convert a C string and its length to a Python object. If the C string
1090 pointer is \NULL{}, the length is ignored and \code{None} is
1091 returned.
1093 \item[\samp{z} (string or \code{None}) {[char *]}]
1094 Same as \samp{s}.
1096 \item[\samp{z\#} (string or \code{None}) {[char *, int]}]
1097 Same as \samp{s\#}.
1099 \item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1100 Convert a null-terminated buffer of Unicode (UCS-2) data to a Python
1101 Unicode object. If the Unicode buffer pointer is \NULL,
1102 \code{None} is returned.
1104 \item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1105 Convert a Unicode (UCS-2) data buffer and its length to a Python
1106 Unicode object. If the Unicode buffer pointer is \NULL, the length
1107 is ignored and \code{None} is returned.
1109 \item[\samp{i} (integer) {[int]}]
1110 Convert a plain C \ctype{int} to a Python integer object.
1112 \item[\samp{b} (integer) {[char]}]
1113 Same as \samp{i}.
1115 \item[\samp{h} (integer) {[short int]}]
1116 Same as \samp{i}.
1118 \item[\samp{l} (integer) {[long int]}]
1119 Convert a C \ctype{long int} to a Python integer object.
1121 \item[\samp{c} (string of length 1) {[char]}]
1122 Convert a C \ctype{int} representing a character to a Python string of
1123 length 1.
1125 \item[\samp{d} (float) {[double]}]
1126 Convert a C \ctype{double} to a Python floating point number.
1128 \item[\samp{f} (float) {[float]}]
1129 Same as \samp{d}.
1131 \item[\samp{D} (complex) {[Py_complex *]}]
1132 Convert a C \ctype{Py_complex} structure to a Python complex number.
1134 \item[\samp{O} (object) {[PyObject *]}]
1135 Pass a Python object untouched (except for its reference count, which
1136 is incremented by one). If the object passed in is a \NULL{}
1137 pointer, it is assumed that this was caused because the call producing
1138 the argument found an error and set an exception. Therefore,
1139 \cfunction{Py_BuildValue()} will return \NULL{} but won't raise an
1140 exception. If no exception has been raised yet,
1141 \cdata{PyExc_SystemError} is set.
1143 \item[\samp{S} (object) {[PyObject *]}]
1144 Same as \samp{O}.
1146 \item[\samp{U} (object) {[PyObject *]}]
1147 Same as \samp{O}.
1149 \item[\samp{N} (object) {[PyObject *]}]
1150 Same as \samp{O}, except it doesn't increment the reference count on
1151 the object. Useful when the object is created by a call to an object
1152 constructor in the argument list.
1154 \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
1155 Convert \var{anything} to a Python object through a \var{converter}
1156 function. The function is called with \var{anything} (which should be
1157 compatible with \ctype{void *}) as its argument and should return a
1158 ``new'' Python object, or \NULL{} if an error occurred.
1160 \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
1161 Convert a sequence of C values to a Python tuple with the same number
1162 of items.
1164 \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
1165 Convert a sequence of C values to a Python list with the same number
1166 of items.
1168 \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
1169 Convert a sequence of C values to a Python dictionary. Each pair of
1170 consecutive C values adds one item to the dictionary, serving as key
1171 and value, respectively.
1173 \end{description}
1175 If there is an error in the format string, the
1176 \cdata{PyExc_SystemError} exception is raised and \NULL{} returned.
1178 Examples (to the left the call, to the right the resulting Python value):
1180 \begin{verbatim}
1181 Py_BuildValue("") None
1182 Py_BuildValue("i", 123) 123
1183 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
1184 Py_BuildValue("s", "hello") 'hello'
1185 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
1186 Py_BuildValue("s#", "hello", 4) 'hell'
1187 Py_BuildValue("()") ()
1188 Py_BuildValue("(i)", 123) (123,)
1189 Py_BuildValue("(ii)", 123, 456) (123, 456)
1190 Py_BuildValue("(i,i)", 123, 456) (123, 456)
1191 Py_BuildValue("[i,i]", 123, 456) [123, 456]
1192 Py_BuildValue("{s:i,s:i}",
1193 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
1194 Py_BuildValue("((ii)(ii)) (ii)",
1195 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
1196 \end{verbatim}
1199 \section{Reference Counts
1200 \label{refcounts}}
1202 In languages like C or \Cpp{}, the programmer is responsible for
1203 dynamic allocation and deallocation of memory on the heap. In C,
1204 this is done using the functions \cfunction{malloc()} and
1205 \cfunction{free()}. In \Cpp{}, the operators \keyword{new} and
1206 \keyword{delete} are used with essentially the same meaning; they are
1207 actually implemented using \cfunction{malloc()} and
1208 \cfunction{free()}, so we'll restrict the following discussion to the
1209 latter.
1211 Every block of memory allocated with \cfunction{malloc()} should
1212 eventually be returned to the pool of available memory by exactly one
1213 call to \cfunction{free()}. It is important to call
1214 \cfunction{free()} at the right time. If a block's address is
1215 forgotten but \cfunction{free()} is not called for it, the memory it
1216 occupies cannot be reused until the program terminates. This is
1217 called a \dfn{memory leak}. On the other hand, if a program calls
1218 \cfunction{free()} for a block and then continues to use the block, it
1219 creates a conflict with re-use of the block through another
1220 \cfunction{malloc()} call. This is called \dfn{using freed memory}.
1221 It has the same bad consequences as referencing uninitialized data ---
1222 core dumps, wrong results, mysterious crashes.
1224 Common causes of memory leaks are unusual paths through the code. For
1225 instance, a function may allocate a block of memory, do some
1226 calculation, and then free the block again. Now a change in the
1227 requirements for the function may add a test to the calculation that
1228 detects an error condition and can return prematurely from the
1229 function. It's easy to forget to free the allocated memory block when
1230 taking this premature exit, especially when it is added later to the
1231 code. Such leaks, once introduced, often go undetected for a long
1232 time: the error exit is taken only in a small fraction of all calls,
1233 and most modern machines have plenty of virtual memory, so the leak
1234 only becomes apparent in a long-running process that uses the leaking
1235 function frequently. Therefore, it's important to prevent leaks from
1236 happening by having a coding convention or strategy that minimizes
1237 this kind of errors.
1239 Since Python makes heavy use of \cfunction{malloc()} and
1240 \cfunction{free()}, it needs a strategy to avoid memory leaks as well
1241 as the use of freed memory. The chosen method is called
1242 \dfn{reference counting}. The principle is simple: every object
1243 contains a counter, which is incremented when a reference to the
1244 object is stored somewhere, and which is decremented when a reference
1245 to it is deleted. When the counter reaches zero, the last reference
1246 to the object has been deleted and the object is freed.
1248 An alternative strategy is called \dfn{automatic garbage collection}.
1249 (Sometimes, reference counting is also referred to as a garbage
1250 collection strategy, hence my use of ``automatic'' to distinguish the
1251 two.) The big advantage of automatic garbage collection is that the
1252 user doesn't need to call \cfunction{free()} explicitly. (Another claimed
1253 advantage is an improvement in speed or memory usage --- this is no
1254 hard fact however.) The disadvantage is that for C, there is no
1255 truly portable automatic garbage collector, while reference counting
1256 can be implemented portably (as long as the functions \cfunction{malloc()}
1257 and \cfunction{free()} are available --- which the C Standard guarantees).
1258 Maybe some day a sufficiently portable automatic garbage collector
1259 will be available for C. Until then, we'll have to live with
1260 reference counts.
1262 \subsection{Reference Counting in Python
1263 \label{refcountsInPython}}
1265 There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
1266 which handle the incrementing and decrementing of the reference count.
1267 \cfunction{Py_DECREF()} also frees the object when the count reaches zero.
1268 For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
1269 makes a call through a function pointer in the object's \dfn{type
1270 object}. For this purpose (and others), every object also contains a
1271 pointer to its type object.
1273 The big question now remains: when to use \code{Py_INCREF(x)} and
1274 \code{Py_DECREF(x)}? Let's first introduce some terms. Nobody
1275 ``owns'' an object; however, you can \dfn{own a reference} to an
1276 object. An object's reference count is now defined as the number of
1277 owned references to it. The owner of a reference is responsible for
1278 calling \cfunction{Py_DECREF()} when the reference is no longer
1279 needed. Ownership of a reference can be transferred. There are three
1280 ways to dispose of an owned reference: pass it on, store it, or call
1281 \cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
1282 creates a memory leak.
1284 It is also possible to \dfn{borrow}\footnote{The metaphor of
1285 ``borrowing'' a reference is not completely correct: the owner still
1286 has a copy of the reference.} a reference to an object. The borrower
1287 of a reference should not call \cfunction{Py_DECREF()}. The borrower must
1288 not hold on to the object longer than the owner from which it was
1289 borrowed. Using a borrowed reference after the owner has disposed of
1290 it risks using freed memory and should be avoided
1291 completely.\footnote{Checking that the reference count is at least 1
1292 \strong{does not work} --- the reference count itself could be in
1293 freed memory and may thus be reused for another object!}
1295 The advantage of borrowing over owning a reference is that you don't
1296 need to take care of disposing of the reference on all possible paths
1297 through the code --- in other words, with a borrowed reference you
1298 don't run the risk of leaking when a premature exit is taken. The
1299 disadvantage of borrowing over leaking is that there are some subtle
1300 situations where in seemingly correct code a borrowed reference can be
1301 used after the owner from which it was borrowed has in fact disposed
1302 of it.
1304 A borrowed reference can be changed into an owned reference by calling
1305 \cfunction{Py_INCREF()}. This does not affect the status of the owner from
1306 which the reference was borrowed --- it creates a new owned reference,
1307 and gives full owner responsibilities (i.e., the new owner must
1308 dispose of the reference properly, as well as the previous owner).
1311 \subsection{Ownership Rules
1312 \label{ownershipRules}}
1314 Whenever an object reference is passed into or out of a function, it
1315 is part of the function's interface specification whether ownership is
1316 transferred with the reference or not.
1318 Most functions that return a reference to an object pass on ownership
1319 with the reference. In particular, all functions whose function it is
1320 to create a new object, e.g.\ \cfunction{PyInt_FromLong()} and
1321 \cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if in
1322 fact, in some cases, you don't receive a reference to a brand new
1323 object, you still receive ownership of the reference. For instance,
1324 \cfunction{PyInt_FromLong()} maintains a cache of popular values and can
1325 return a reference to a cached item.
1327 Many functions that extract objects from other objects also transfer
1328 ownership with the reference, for instance
1329 \cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
1330 however, since a few common routines are exceptions:
1331 \cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
1332 \cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
1333 all return references that you borrow from the tuple, list or
1334 dictionary.
1336 The function \cfunction{PyImport_AddModule()} also returns a borrowed
1337 reference, even though it may actually create the object it returns:
1338 this is possible because an owned reference to the object is stored in
1339 \code{sys.modules}.
1341 When you pass an object reference into another function, in general,
1342 the function borrows the reference from you --- if it needs to store
1343 it, it will use \cfunction{Py_INCREF()} to become an independent
1344 owner. There are exactly two important exceptions to this rule:
1345 \cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
1346 functions take over ownership of the item passed to them --- even if
1347 they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
1348 take over ownership --- they are ``normal.'')
1350 When a C function is called from Python, it borrows references to its
1351 arguments from the caller. The caller owns a reference to the object,
1352 so the borrowed reference's lifetime is guaranteed until the function
1353 returns. Only when such a borrowed reference must be stored or passed
1354 on, it must be turned into an owned reference by calling
1355 \cfunction{Py_INCREF()}.
1357 The object reference returned from a C function that is called from
1358 Python must be an owned reference --- ownership is tranferred from the
1359 function to its caller.
1362 \subsection{Thin Ice
1363 \label{thinIce}}
1365 There are a few situations where seemingly harmless use of a borrowed
1366 reference can lead to problems. These all have to do with implicit
1367 invocations of the interpreter, which can cause the owner of a
1368 reference to dispose of it.
1370 The first and most important case to know about is using
1371 \cfunction{Py_DECREF()} on an unrelated object while borrowing a
1372 reference to a list item. For instance:
1374 \begin{verbatim}
1375 bug(PyObject *list) {
1376 PyObject *item = PyList_GetItem(list, 0);
1378 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1379 PyObject_Print(item, stdout, 0); /* BUG! */
1381 \end{verbatim}
1383 This function first borrows a reference to \code{list[0]}, then
1384 replaces \code{list[1]} with the value \code{0}, and finally prints
1385 the borrowed reference. Looks harmless, right? But it's not!
1387 Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
1388 owns references to all its items, so when item 1 is replaced, it has
1389 to dispose of the original item 1. Now let's suppose the original
1390 item 1 was an instance of a user-defined class, and let's further
1391 suppose that the class defined a \method{__del__()} method. If this
1392 class instance has a reference count of 1, disposing of it will call
1393 its \method{__del__()} method.
1395 Since it is written in Python, the \method{__del__()} method can execute
1396 arbitrary Python code. Could it perhaps do something to invalidate
1397 the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
1398 that the list passed into \cfunction{bug()} is accessible to the
1399 \method{__del__()} method, it could execute a statement to the effect of
1400 \samp{del list[0]}, and assuming this was the last reference to that
1401 object, it would free the memory associated with it, thereby
1402 invalidating \code{item}.
1404 The solution, once you know the source of the problem, is easy:
1405 temporarily increment the reference count. The correct version of the
1406 function reads:
1408 \begin{verbatim}
1409 no_bug(PyObject *list) {
1410 PyObject *item = PyList_GetItem(list, 0);
1412 Py_INCREF(item);
1413 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1414 PyObject_Print(item, stdout, 0);
1415 Py_DECREF(item);
1417 \end{verbatim}
1419 This is a true story. An older version of Python contained variants
1420 of this bug and someone spent a considerable amount of time in a C
1421 debugger to figure out why his \method{__del__()} methods would fail...
1423 The second case of problems with a borrowed reference is a variant
1424 involving threads. Normally, multiple threads in the Python
1425 interpreter can't get in each other's way, because there is a global
1426 lock protecting Python's entire object space. However, it is possible
1427 to temporarily release this lock using the macro
1428 \code{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
1429 \code{Py_END_ALLOW_THREADS}. This is common around blocking I/O
1430 calls, to let other threads use the CPU while waiting for the I/O to
1431 complete. Obviously, the following function has the same problem as
1432 the previous one:
1434 \begin{verbatim}
1435 bug(PyObject *list) {
1436 PyObject *item = PyList_GetItem(list, 0);
1437 Py_BEGIN_ALLOW_THREADS
1438 ...some blocking I/O call...
1439 Py_END_ALLOW_THREADS
1440 PyObject_Print(item, stdout, 0); /* BUG! */
1442 \end{verbatim}
1445 \subsection{NULL Pointers
1446 \label{nullPointers}}
1448 In general, functions that take object references as arguments do not
1449 expect you to pass them \NULL{} pointers, and will dump core (or
1450 cause later core dumps) if you do so. Functions that return object
1451 references generally return \NULL{} only to indicate that an
1452 exception occurred. The reason for not testing for \NULL{}
1453 arguments is that functions often pass the objects they receive on to
1454 other function --- if each function were to test for \NULL{},
1455 there would be a lot of redundant tests and the code would run more
1456 slowly.
1458 It is better to test for \NULL{} only at the ``source'', i.e.\ when a
1459 pointer that may be \NULL{} is received, e.g.\ from
1460 \cfunction{malloc()} or from a function that may raise an exception.
1462 The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
1463 do not check for \NULL{} pointers --- however, their variants
1464 \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
1466 The macros for checking for a particular object type
1467 (\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
1468 again, there is much code that calls several of these in a row to test
1469 an object against various different expected types, and this would
1470 generate redundant tests. There are no variants with \NULL{}
1471 checking.
1473 The C function calling mechanism guarantees that the argument list
1474 passed to C functions (\code{args} in the examples) is never
1475 \NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
1476 These guarantees don't hold when you use the ``old'' style
1477 calling convention --- this is still found in much existing code.}
1479 It is a severe error to ever let a \NULL{} pointer ``escape'' to
1480 the Python user.
1482 % Frank Stajano:
1483 % A pedagogically buggy example, along the lines of the previous listing,
1484 % would be helpful here -- showing in more concrete terms what sort of
1485 % actions could cause the problem. I can't very well imagine it from the
1486 % description.
1489 \section{Writing Extensions in \Cpp{}
1490 \label{cplusplus}}
1492 It is possible to write extension modules in \Cpp{}. Some restrictions
1493 apply. If the main program (the Python interpreter) is compiled and
1494 linked by the C compiler, global or static objects with constructors
1495 cannot be used. This is not a problem if the main program is linked
1496 by the \Cpp{} compiler. Functions that will be called by the
1497 Python interpreter (in particular, module initalization functions)
1498 have to be declared using \code{extern "C"}.
1499 It is unnecessary to enclose the Python header files in
1500 \code{extern "C" \{...\}} --- they use this form already if the symbol
1501 \samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
1502 symbol).
1505 \section{Providing a C API for an Extension Module
1506 \label{using-cobjects}}
1507 \sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
1509 Many extension modules just provide new functions and types to be
1510 used from Python, but sometimes the code in an extension module can
1511 be useful for other extension modules. For example, an extension
1512 module could implement a type ``collection'' which works like lists
1513 without order. Just like the standard Python list type has a C API
1514 which permits extension modules to create and manipulate lists, this
1515 new collection type should have a set of C functions for direct
1516 manipulation from other extension modules.
1518 At first sight this seems easy: just write the functions (without
1519 declaring them \keyword{static}, of course), provide an appropriate
1520 header file, and document the C API. And in fact this would work if
1521 all extension modules were always linked statically with the Python
1522 interpreter. When modules are used as shared libraries, however, the
1523 symbols defined in one module may not be visible to another module.
1524 The details of visibility depend on the operating system; some systems
1525 use one global namespace for the Python interpreter and all extension
1526 modules (e.g.\ Windows), whereas others require an explicit list of
1527 imported symbols at module link time (e.g.\ AIX), or offer a choice of
1528 different strategies (most Unices). And even if symbols are globally
1529 visible, the module whose functions one wishes to call might not have
1530 been loaded yet!
1532 Portability therefore requires not to make any assumptions about
1533 symbol visibility. This means that all symbols in extension modules
1534 should be declared \keyword{static}, except for the module's
1535 initialization function, in order to avoid name clashes with other
1536 extension modules (as discussed in section~\ref{methodTable}). And it
1537 means that symbols that \emph{should} be accessible from other
1538 extension modules must be exported in a different way.
1540 Python provides a special mechanism to pass C-level information (i.e.
1541 pointers) from one extension module to another one: CObjects.
1542 A CObject is a Python data type which stores a pointer (\ctype{void
1543 *}). CObjects can only be created and accessed via their C API, but
1544 they can be passed around like any other Python object. In particular,
1545 they can be assigned to a name in an extension module's namespace.
1546 Other extension modules can then import this module, retrieve the
1547 value of this name, and then retrieve the pointer from the CObject.
1549 There are many ways in which CObjects can be used to export the C API
1550 of an extension module. Each name could get its own CObject, or all C
1551 API pointers could be stored in an array whose address is published in
1552 a CObject. And the various tasks of storing and retrieving the pointers
1553 can be distributed in different ways between the module providing the
1554 code and the client modules.
1556 The following example demonstrates an approach that puts most of the
1557 burden on the writer of the exporting module, which is appropriate
1558 for commonly used library modules. It stores all C API pointers
1559 (just one in the example!) in an array of \ctype{void} pointers which
1560 becomes the value of a CObject. The header file corresponding to
1561 the module provides a macro that takes care of importing the module
1562 and retrieving its C API pointers; client modules only have to call
1563 this macro before accessing the C API.
1565 The exporting module is a modification of the \module{spam} module from
1566 section~\ref{simpleExample}. The function \function{spam.system()}
1567 does not call the C library function \cfunction{system()} directly,
1568 but a function \cfunction{PySpam_System()}, which would of course do
1569 something more complicated in reality (such as adding ``spam'' to
1570 every command). This function \cfunction{PySpam_System()} is also
1571 exported to other extension modules.
1573 The function \cfunction{PySpam_System()} is a plain C function,
1574 declared \keyword{static} like everything else:
1576 \begin{verbatim}
1577 static int
1578 PySpam_System(command)
1579 char *command;
1581 return system(command);
1583 \end{verbatim}
1585 The function \cfunction{spam_system()} is modified in a trivial way:
1587 \begin{verbatim}
1588 static PyObject *
1589 spam_system(self, args)
1590 PyObject *self;
1591 PyObject *args;
1593 char *command;
1594 int sts;
1596 if (!PyArg_ParseTuple(args, "s", &command))
1597 return NULL;
1598 sts = PySpam_System(command);
1599 return Py_BuildValue("i", sts);
1601 \end{verbatim}
1603 In the beginning of the module, right after the line
1605 \begin{verbatim}
1606 #include "Python.h"
1607 \end{verbatim}
1609 two more lines must be added:
1611 \begin{verbatim}
1612 #define SPAM_MODULE
1613 #include "spammodule.h"
1614 \end{verbatim}
1616 The \code{\#define} is used to tell the header file that it is being
1617 included in the exporting module, not a client module. Finally,
1618 the module's initialization function must take care of initializing
1619 the C API pointer array:
1621 \begin{verbatim}
1622 void
1623 initspam()
1625 PyObject *m;
1626 static void *PySpam_API[PySpam_API_pointers];
1627 PyObject *c_api_object;
1629 m = Py_InitModule("spam", SpamMethods);
1631 /* Initialize the C API pointer array */
1632 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1634 /* Create a CObject containing the API pointer array's address */
1635 c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
1637 if (c_api_object != NULL) {
1638 /* Create a name for this object in the module's namespace */
1639 PyObject *d = PyModule_GetDict(m);
1641 PyDict_SetItemString(d, "_C_API", c_api_object);
1642 Py_DECREF(c_api_object);
1645 \end{verbatim}
1647 Note that \code{PySpam_API} is declared \code{static}; otherwise
1648 the pointer array would disappear when \code{initspam} terminates!
1650 The bulk of the work is in the header file \file{spammodule.h},
1651 which looks like this:
1653 \begin{verbatim}
1654 #ifndef Py_SPAMMODULE_H
1655 #define Py_SPAMMODULE_H
1656 #ifdef __cplusplus
1657 extern "C" {
1658 #endif
1660 /* Header file for spammodule */
1662 /* C API functions */
1663 #define PySpam_System_NUM 0
1664 #define PySpam_System_RETURN int
1665 #define PySpam_System_PROTO (char *command)
1667 /* Total number of C API pointers */
1668 #define PySpam_API_pointers 1
1671 #ifdef SPAM_MODULE
1672 /* This section is used when compiling spammodule.c */
1674 static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1676 #else
1677 /* This section is used in modules that use spammodule's API */
1679 static void **PySpam_API;
1681 #define PySpam_System \
1682 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1684 #define import_spam() \
1686 PyObject *module = PyImport_ImportModule("spam"); \
1687 if (module != NULL) { \
1688 PyObject *module_dict = PyModule_GetDict(module); \
1689 PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
1690 if (PyCObject_Check(c_api_object)) { \
1691 PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
1696 #endif
1698 #ifdef __cplusplus
1700 #endif
1702 #endif /* !defined(Py_SPAMMODULE_H */
1703 \end{verbatim}
1705 All that a client module must do in order to have access to the
1706 function \cfunction{PySpam_System()} is to call the function (or
1707 rather macro) \cfunction{import_spam()} in its initialization
1708 function:
1710 \begin{verbatim}
1711 void
1712 initclient()
1714 PyObject *m;
1716 Py_InitModule("client", ClientMethods);
1717 import_spam();
1719 \end{verbatim}
1721 The main disadvantage of this approach is that the file
1722 \file{spammodule.h} is rather complicated. However, the
1723 basic structure is the same for each function that is
1724 exported, so it has to be learned only once.
1726 Finally it should be mentioned that CObjects offer additional
1727 functionality, which is especially useful for memory allocation and
1728 deallocation of the pointer stored in a CObject. The details
1729 are described in the \citetitle[../api/api.html]{Python/C API
1730 Reference Manual} in the section ``CObjects'' and in the
1731 implementation of CObjects (files \file{Include/cobject.h} and
1732 \file{Objects/cobject.c} in the Python source code distribution).
1735 \chapter{Defining New Types
1736 \label{defining-new-types}}
1737 \sectionauthor{Michael Hudson}{mwh21@cam.ac.uk}
1739 As mentioned in the last chapter, Python allows the writer of an
1740 extension module to define new types that can be manipulated from
1741 Python code, much like strings and lists in core Python.
1743 This is not hard; the code for all extension types follows a pattern,
1744 but there are some details that you need to understand before you can
1745 get started.
1747 \section{The Basics
1748 \label{dnt-basics}}
1750 The Python runtime sees all Python objects as variables of type
1751 \ctype{PyObject*}. A \ctype{PyObject} is not a very magnificent
1752 object - it just contains the refcount and a pointer to the object's
1753 ``type object''. This is where the action is; the type object
1754 determines which (C) functions get called when, for instance, an
1755 attribute gets looked up on an object or it is multiplied by another
1756 object. I call these C functions ``type methods'' to distinguish them
1757 from things like \code{[].append} (which I will call ``object
1758 methods'' when I get around to them).
1760 So, if you want to define a new object type, you need to create a new
1761 type object.
1763 This sort of thing can only be explained by example, so here's a
1764 minimal, but complete, module that defines a new type:
1766 \begin{verbatim}
1767 #include <Python.h>
1769 staticforward PyTypeObject noddy_NoddyType;
1771 typedef struct {
1772 PyObject_HEAD
1773 } noddy_NoddyObject;
1775 static PyObject*
1776 noddy_new_noddy(PyObject* self, PyObject* args)
1778 noddy_NoddyObject* noddy;
1780 if (!PyArg_ParseTuple(args,":new_noddy"))
1781 return NULL;
1783 noddy = PyObject_New(noddy_NoddyObject, &noddy_NoddyType);
1785 return (PyObject*)noddy;
1788 static void
1789 noddy_noddy_dealloc(PyObject* self)
1791 PyObject_Del(self);
1794 static PyTypeObject noddy_NoddyType = {
1795 PyObject_HEAD_INIT(NULL)
1797 "Noddy",
1798 sizeof(noddy_NoddyObject),
1800 noddy_noddy_dealloc, /*tp_dealloc*/
1801 0, /*tp_print*/
1802 0, /*tp_getattr*/
1803 0, /*tp_setattr*/
1804 0, /*tp_compare*/
1805 0, /*tp_repr*/
1806 0, /*tp_as_number*/
1807 0, /*tp_as_sequence*/
1808 0, /*tp_as_mapping*/
1809 0, /*tp_hash */
1812 static PyMethodDef noddy_methods[] = {
1813 { "new_noddy", noddy_new_noddy, METH_VARARGS },
1814 {NULL, NULL}
1817 DL_EXPORT(void)
1818 initnoddy(void)
1820 noddy_NoddyType.ob_type = &PyType_Type;
1822 Py_InitModule("noddy", noddy_methods);
1824 \end{verbatim}
1826 Now that's quite a bit to take in at once, but hopefully bits will
1827 seem familiar from the last chapter.
1829 The first bit that will be new is:
1831 \begin{verbatim}
1832 staticforward PyTypeObject noddy_NoddyType;
1833 \end{verbatim}
1835 This names the type object that will be defining further down in the
1836 file. It can't be defined here because its definition has to refer to
1837 functions that have no yet been defined, but we need to be able to
1838 refer to it, hence the declaration.
1840 The \code{staticforward} is required to placate various brain dead
1841 compilers.
1843 \begin{verbatim}
1844 typedef struct {
1845 PyObject_HEAD
1846 } noddy_NoddyObject;
1847 \end{verbatim}
1849 This is what a Noddy object will contain. In this case nothing more
1850 than every Python object contains - a refcount and a pointer to a type
1851 object. These are the fields the \code{PyObject_HEAD} macro brings
1852 in. The reason for the macro is to standardize the layout and to
1853 enable special debugging fields to be brought in debug builds.
1855 For contrast
1857 \begin{verbatim}
1858 typedef struct {
1859 PyObject_HEAD
1860 long ob_ival;
1861 } PyIntObject;
1862 \end{verbatim}
1864 is the corresponding definition for standard Python integers.
1866 Next up is:
1868 \begin{verbatim}
1869 static PyObject*
1870 noddy_new_noddy(PyObject* self, PyObject* args)
1872 noddy_NoddyObject* noddy;
1874 if (!PyArg_ParseTuple(args,":new_noddy"))
1875 return NULL;
1877 noddy = PyObject_New(noddy_NoddyObject, &noddy_NoddyType);
1879 return (PyObject*)noddy;
1881 \end{verbatim}
1883 This is in fact just a regular module function, as described in the
1884 last chapter. The reason it gets special mention is that this is
1885 where we create our Noddy object. Defining PyTypeObject structures is
1886 all very well, but if there's no way to actually \emph{create} one
1887 of the wretched things it is not going to do anyone much good.
1889 Almost always, you create objects with a call of the form:
1891 \begin{verbatim}
1892 PyObject_New(<type>, &<type object>);
1893 \end{verbatim}
1895 This allocates the memory and then initializes the object (i.e.\ sets
1896 the reference count to one, makes the \cdata{ob_type} pointer point at
1897 the right place and maybe some other stuff, depending on build options).
1898 You \emph{can} do these steps separately if you have some reason to
1899 --- but at this level we don't bother.
1901 We cast the return value to a \ctype{PyObject*} because that's what
1902 the Python runtime expects. This is safe because of guarantees about
1903 the layout of structures in the C standard, and is a fairly common C
1904 programming trick. One could declare \cfunction{noddy_new_noddy} to
1905 return a \ctype{noddy_NoddyObject*} and then put a cast in the
1906 definition of \cdata{noddy_methods} further down the file --- it
1907 doesn't make much difference.
1909 Now a Noddy object doesn't do very much and so doesn't need to
1910 implement many type methods. One you can't avoid is handling
1911 deallocation, so we find
1913 \begin{verbatim}
1914 static void
1915 noddy_noddy_dealloc(PyObject* self)
1917 PyObject_Del(self);
1919 \end{verbatim}
1921 This is so short as to be self explanatory. This function will be
1922 called when the reference count on a Noddy object reaches \code{0} (or
1923 it is found as part of an unreachable cycle by the cyclic garbage
1924 collector). \cfunction{PyObject_Del()} is what you call when you want
1925 an object to go away. If a Noddy object held references to other
1926 Python objects, one would decref them here.
1928 Moving on, we come to the crunch --- the type object.
1930 \begin{verbatim}
1931 static PyTypeObject noddy_NoddyType = {
1932 PyObject_HEAD_INIT(NULL)
1934 "Noddy",
1935 sizeof(noddy_NoddyObject),
1937 noddy_noddy_dealloc, /*tp_dealloc*/
1938 0, /*tp_print*/
1939 0, /*tp_getattr*/
1940 0, /*tp_setattr*/
1941 0, /*tp_compare*/
1942 0, /*tp_repr*/
1943 0, /*tp_as_number*/
1944 0, /*tp_as_sequence*/
1945 0, /*tp_as_mapping*/
1946 0, /*tp_hash */
1948 \end{verbatim}
1950 Now if you go and look up the definition of \ctype{PyTypeObject} in
1951 \file{object.h} you'll see that it has many, many more fields that the
1952 definition above. The remaining fields will be filled with zeros by
1953 the C compiler, and it's common practice to not specify them
1954 explicitly unless you need them.
1956 This is so important that I'm going to pick the top of it apart still
1957 further:
1959 \begin{verbatim}
1960 PyObject_HEAD_INIT(NULL)
1961 \end{verbatim}
1963 This line is a bit of a wart; what we'd like to write is:
1965 \begin{verbatim}
1966 PyObject_HEAD_INIT(&PyType_Type)
1967 \end{verbatim}
1969 as the type of a type object is ``type'', but this isn't strictly
1970 conforming C and some compilers complain. So instead we fill in the
1971 \cdata{ob_type} field of \cdata{noddy_NoddyType} at the earliest
1972 oppourtunity --- in \cfunction{initnoddy()}.
1974 \begin{verbatim}
1976 \end{verbatim}
1978 XXX why does the type info struct start PyObject_*VAR*_HEAD??
1980 \begin{verbatim}
1981 "Noddy",
1982 \end{verbatim}
1984 The name of our type. This will appear in the default textual
1985 representation of our objects and in some error messages, for example:
1987 \begin{verbatim}
1988 >>> "" + noddy.new_noddy()
1989 Traceback (most recent call last):
1990 File "<stdin>", line 1, in ?
1991 TypeError: cannot add type "Noddy" to string
1992 \end{verbatim}
1994 \begin{verbatim}
1995 sizeof(noddy_NoddyObject),
1996 \end{verbatim}
1998 This is so that Python knows how much memory to allocate when you call
1999 \cfunction{PyObject_New}.
2001 \begin{verbatim}
2003 \end{verbatim}
2005 This has to do with variable length objects like lists and strings.
2006 Ignore for now...
2008 Now we get into the type methods, the things that make your objects
2009 different from the others. Of course, the Noddy object doesn't
2010 implement many of these, but as mentioned above you have to implement
2011 the deallocation function.
2013 \begin{verbatim}
2014 noddy_noddy_dealloc, /*tp_dealloc*/
2015 \end{verbatim}
2017 From here, all the type methods are nil so I won't go over them yet -
2018 that's for the next section!
2020 Everything else in the file should be familiar, except for this line
2021 in \cfunction{initnoddy}:
2023 \begin{verbatim}
2024 noddy_NoddyType.ob_type = &PyType_Type;
2025 \end{verbatim}
2027 This was alluded to above --- the \cdata{noddy_NoddyType} object should
2028 have type ``type'', but \code{\&PyType_Type} is not constant and so
2029 can't be used in its initializer. To work around this, we patch it up
2030 in the module initialization.
2032 That's it! All that remains is to build it; put the above code in a
2033 file called \file{noddymodule.c} and
2035 \begin{verbatim}
2036 from distutils.core import setup, Extension
2037 setup(name = "noddy", version = "1.0",
2038 ext_modules = [Extension("noddy", ["noddymodule.c"])])
2039 \end{verbatim}
2041 in a file called \file{setup.py}; then typing
2043 \begin{verbatim}
2044 $ python setup.py build%$
2045 \end{verbatim}
2047 at a shell should produce a file \file{noddy.so} in a subdirectory;
2048 move to that directory and fire up Python --- you should be able to
2049 \code{import noddy} and play around with Noddy objects.
2051 That wasn't so hard, was it?
2053 \section{Type Methods
2054 \label{dnt-type-methods}}
2056 This section aims to give a quick fly-by on the various type methods
2057 you can implement and what they do.
2059 Here is the definition of \ctype{PyTypeObject}, with some fields only
2060 used in debug builds omitted:
2062 \begin{verbatim}
2063 typedef struct _typeobject {
2064 PyObject_VAR_HEAD
2065 char *tp_name; /* For printing */
2066 int tp_basicsize, tp_itemsize; /* For allocation */
2068 /* Methods to implement standard operations */
2070 destructor tp_dealloc;
2071 printfunc tp_print;
2072 getattrfunc tp_getattr;
2073 setattrfunc tp_setattr;
2074 cmpfunc tp_compare;
2075 reprfunc tp_repr;
2077 /* Method suites for standard classes */
2079 PyNumberMethods *tp_as_number;
2080 PySequenceMethods *tp_as_sequence;
2081 PyMappingMethods *tp_as_mapping;
2083 /* More standard operations (here for binary compatibility) */
2085 hashfunc tp_hash;
2086 ternaryfunc tp_call;
2087 reprfunc tp_str;
2088 getattrofunc tp_getattro;
2089 setattrofunc tp_setattro;
2091 /* Functions to access object as input/output buffer */
2092 PyBufferProcs *tp_as_buffer;
2094 /* Flags to define presence of optional/expanded features */
2095 long tp_flags;
2097 char *tp_doc; /* Documentation string */
2099 /* call function for all accessible objects */
2100 traverseproc tp_traverse;
2102 /* delete references to contained objects */
2103 inquiry tp_clear;
2105 /* rich comparisons */
2106 richcmpfunc tp_richcompare;
2108 /* weak reference enabler */
2109 long tp_weaklistoffset;
2111 } PyTypeObject;
2112 \end{verbatim}
2114 Now that's a \emph{lot} of methods. Don't worry too much though - if
2115 you have a type you want to define, the chances are very good that you
2116 will only implement a handful of these.
2118 As you probably expect by now, I'm going to go over this line-by-line,
2119 saying a word about each field as we get to it.
2121 \begin{verbatim}
2122 char *tp_name; /* For printing */
2123 \end{verbatim}
2125 The name of the type - as mentioned in the last section, this will
2126 appear in various places, almost entirely for diagnostic purposes.
2127 Try to choose something that will be helpful in such a situation!
2129 \begin{verbatim}
2130 int tp_basicsize, tp_itemsize; /* For allocation */
2131 \end{verbatim}
2133 These fields tell the runtime how much memory to allocate when new
2134 objects of this typed are created. Python has some builtin support
2135 for variable length structures (think: strings, lists) which is where
2136 the \cdata{tp_itemsize} field comes in. This will be dealt with
2137 later.
2139 Now we come to the basic type methods - the ones most extension types
2140 will implement.
2142 \begin{verbatim}
2143 destructor tp_dealloc;
2144 printfunc tp_print;
2145 getattrfunc tp_getattr;
2146 setattrfunc tp_setattr;
2147 cmpfunc tp_compare;
2148 reprfunc tp_repr;
2149 \end{verbatim}
2152 %\section{Attributes \& Methods
2153 % \label{dnt-attrs-and-meths}}
2156 \chapter{Building C and \Cpp{} Extensions on \UNIX{}
2157 \label{building-on-unix}}
2159 \sectionauthor{Jim Fulton}{jim@Digicool.com}
2162 %The make file make file, building C extensions on Unix
2165 Starting in Python 1.4, Python provides a special make file for
2166 building make files for building dynamically-linked extensions and
2167 custom interpreters. The make file make file builds a make file
2168 that reflects various system variables determined by configure when
2169 the Python interpreter was built, so people building module's don't
2170 have to resupply these settings. This vastly simplifies the process
2171 of building extensions and custom interpreters on Unix systems.
2173 The make file make file is distributed as the file
2174 \file{Misc/Makefile.pre.in} in the Python source distribution. The
2175 first step in building extensions or custom interpreters is to copy
2176 this make file to a development directory containing extension module
2177 source.
2179 The make file make file, \file{Makefile.pre.in} uses metadata
2180 provided in a file named \file{Setup}. The format of the \file{Setup}
2181 file is the same as the \file{Setup} (or \file{Setup.dist}) file
2182 provided in the \file{Modules/} directory of the Python source
2183 distribution. The \file{Setup} file contains variable definitions:
2185 \begin{verbatim}
2186 EC=/projects/ExtensionClass
2187 \end{verbatim}
2189 and module description lines. It can also contain blank lines and
2190 comment lines that start with \character{\#}.
2192 A module description line includes a module name, source files,
2193 options, variable references, and other input files, such
2194 as libraries or object files. Consider a simple example:
2196 \begin{verbatim}
2197 ExtensionClass ExtensionClass.c
2198 \end{verbatim}
2200 This is the simplest form of a module definition line. It defines a
2201 module, \module{ExtensionClass}, which has a single source file,
2202 \file{ExtensionClass.c}.
2204 This slightly more complex example uses an \strong{-I} option to
2205 specify an include directory:
2207 \begin{verbatim}
2208 EC=/projects/ExtensionClass
2209 cPersistence cPersistence.c -I$(EC)
2210 \end{verbatim} % $ <-- bow to font lock
2212 This example also illustrates the format for variable references.
2214 For systems that support dynamic linking, the \file{Setup} file should
2215 begin:
2217 \begin{verbatim}
2218 *shared*
2219 \end{verbatim}
2221 to indicate that the modules defined in \file{Setup} are to be built
2222 as dynamically linked modules. A line containing only \samp{*static*}
2223 can be used to indicate the subsequently listed modules should be
2224 statically linked.
2226 Here is a complete \file{Setup} file for building a
2227 \module{cPersistent} module:
2229 \begin{verbatim}
2230 # Set-up file to build the cPersistence module.
2231 # Note that the text should begin in the first column.
2232 *shared*
2234 # We need the path to the directory containing the ExtensionClass
2235 # include file.
2236 EC=/projects/ExtensionClass
2237 cPersistence cPersistence.c -I$(EC)
2238 \end{verbatim} % $ <-- bow to font lock
2240 After the \file{Setup} file has been created, \file{Makefile.pre.in}
2241 is run with the \samp{boot} target to create a make file:
2243 \begin{verbatim}
2244 make -f Makefile.pre.in boot
2245 \end{verbatim}
2247 This creates the file, Makefile. To build the extensions, simply
2248 run the created make file:
2250 \begin{verbatim}
2251 make
2252 \end{verbatim}
2254 It's not necessary to re-run \file{Makefile.pre.in} if the
2255 \file{Setup} file is changed. The make file automatically rebuilds
2256 itself if the \file{Setup} file changes.
2259 \section{Building Custom Interpreters \label{custom-interps}}
2261 The make file built by \file{Makefile.pre.in} can be run with the
2262 \samp{static} target to build an interpreter:
2264 \begin{verbatim}
2265 make static
2266 \end{verbatim}
2268 Any modules defined in the \file{Setup} file before the
2269 \samp{*shared*} line will be statically linked into the interpreter.
2270 Typically, a \samp{*shared*} line is omitted from the
2271 \file{Setup} file when a custom interpreter is desired.
2274 \section{Module Definition Options \label{module-defn-options}}
2276 Several compiler options are supported:
2278 \begin{tableii}{l|l}{programopt}{Option}{Meaning}
2279 \lineii{-C}{Tell the C pre-processor not to discard comments}
2280 \lineii{-D\var{name}=\var{value}}{Define a macro}
2281 \lineii{-I\var{dir}}{Specify an include directory, \var{dir}}
2282 \lineii{-L\var{dir}}{Specify a link-time library directory, \var{dir}}
2283 \lineii{-R\var{dir}}{Specify a run-time library directory, \var{dir}}
2284 \lineii{-l\var{lib}}{Link a library, \var{lib}}
2285 \lineii{-U\var{name}}{Undefine a macro}
2286 \end{tableii}
2288 Other compiler options can be included (snuck in) by putting them
2289 in variables.
2291 Source files can include files with \file{.c}, \file{.C}, \file{.cc},
2292 \file{.cpp}, \file{.cxx}, and \file{.c++} extensions.
2294 Other input files include files with \file{.a}, \file{.o}, \file{.sl},
2295 and \file{.so} extensions.
2298 \section{Example \label{module-defn-example}}
2300 Here is a more complicated example from \file{Modules/Setup.dist}:
2302 \begin{verbatim}
2303 GMP=/ufs/guido/src/gmp
2304 mpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a
2305 \end{verbatim}
2307 which could also be written as:
2309 \begin{verbatim}
2310 mpz mpzmodule.c -I$(GMP) -L$(GMP) -lgmp
2311 \end{verbatim}
2314 \section{Distributing your extension modules
2315 \label{distributing}}
2317 There are two ways to distribute extension modules for others to use.
2318 The way that allows the easiest cross-platform support is to use the
2319 \module{distutils}\refstmodindex{distutils} package. The manual
2320 \citetitle[../dist/dist.html]{Distributing Python Modules} contains
2321 information on this approach. It is recommended that all new
2322 extensions be distributed using this approach to allow easy building
2323 and installation across platforms. Older extensions should migrate to
2324 this approach as well.
2326 What follows describes the older approach; there are still many
2327 extensions which use this.
2329 When distributing your extension modules in source form, make sure to
2330 include a \file{Setup} file. The \file{Setup} file should be named
2331 \file{Setup.in} in the distribution. The make file make file,
2332 \file{Makefile.pre.in}, will copy \file{Setup.in} to \file{Setup} if
2333 the person installing the extension doesn't do so manually.
2334 Distributing a \file{Setup.in} file makes it easy for people to
2335 customize the \file{Setup} file while keeping the original in
2336 \file{Setup.in}.
2338 It is a good idea to include a copy of \file{Makefile.pre.in} for
2339 people who do not have a source distribution of Python.
2341 Do not distribute a make file. People building your modules
2342 should use \file{Makefile.pre.in} to build their own make file. A
2343 \file{README} file included in the package should provide simple
2344 instructions to perform the build.
2347 \chapter{Building C and \Cpp{} Extensions on Windows
2348 \label{building-on-windows}}
2351 This chapter briefly explains how to create a Windows extension module
2352 for Python using Microsoft Visual \Cpp{}, and follows with more
2353 detailed background information on how it works. The explanatory
2354 material is useful for both the Windows programmer learning to build
2355 Python extensions and the \UNIX{} programmer interested in producing
2356 software which can be successfully built on both \UNIX{} and Windows.
2359 \section{A Cookbook Approach \label{win-cookbook}}
2361 \sectionauthor{Neil Schemenauer}{neil_schemenauer@transcanada.com}
2363 This section provides a recipe for building a Python extension on
2364 Windows.
2366 Grab the binary installer from \url{http://www.python.org/} and
2367 install Python. The binary installer has all of the required header
2368 files except for \file{config.h}.
2370 Get the source distribution and extract it into a convenient location.
2371 Copy the \file{config.h} from the \file{PC/} directory into the
2372 \file{include/} directory created by the installer.
2374 Create a \file{Setup} file for your extension module, as described in
2375 chapter \ref{building-on-unix}.
2377 Get David Ascher's \file{compile.py} script from
2378 \url{http://starship.python.net/crew/da/compile/}. Run the script to
2379 create Microsoft Visual \Cpp{} project files.
2381 Open the DSW file in Visual \Cpp{} and select \strong{Build}.
2383 If your module creates a new type, you may have trouble with this line:
2385 \begin{verbatim}
2386 PyObject_HEAD_INIT(&PyType_Type)
2387 \end{verbatim}
2389 Change it to:
2391 \begin{verbatim}
2392 PyObject_HEAD_INIT(NULL)
2393 \end{verbatim}
2395 and add the following to the module initialization function:
2397 \begin{verbatim}
2398 MyObject_Type.ob_type = &PyType_Type;
2399 \end{verbatim}
2401 Refer to section 3 of the
2402 \citetitle[http://www.python.org/doc/FAQ.html]{Python FAQ} for details
2403 on why you must do this.
2406 \section{Differences Between \UNIX{} and Windows
2407 \label{dynamic-linking}}
2408 \sectionauthor{Chris Phoenix}{cphoenix@best.com}
2411 \UNIX{} and Windows use completely different paradigms for run-time
2412 loading of code. Before you try to build a module that can be
2413 dynamically loaded, be aware of how your system works.
2415 In \UNIX{}, a shared object (\file{.so}) file contains code to be used by the
2416 program, and also the names of functions and data that it expects to
2417 find in the program. When the file is joined to the program, all
2418 references to those functions and data in the file's code are changed
2419 to point to the actual locations in the program where the functions
2420 and data are placed in memory. This is basically a link operation.
2422 In Windows, a dynamic-link library (\file{.dll}) file has no dangling
2423 references. Instead, an access to functions or data goes through a
2424 lookup table. So the DLL code does not have to be fixed up at runtime
2425 to refer to the program's memory; instead, the code already uses the
2426 DLL's lookup table, and the lookup table is modified at runtime to
2427 point to the functions and data.
2429 In \UNIX{}, there is only one type of library file (\file{.a}) which
2430 contains code from several object files (\file{.o}). During the link
2431 step to create a shared object file (\file{.so}), the linker may find
2432 that it doesn't know where an identifier is defined. The linker will
2433 look for it in the object files in the libraries; if it finds it, it
2434 will include all the code from that object file.
2436 In Windows, there are two types of library, a static library and an
2437 import library (both called \file{.lib}). A static library is like a
2438 \UNIX{} \file{.a} file; it contains code to be included as necessary.
2439 An import library is basically used only to reassure the linker that a
2440 certain identifier is legal, and will be present in the program when
2441 the DLL is loaded. So the linker uses the information from the
2442 import library to build the lookup table for using identifiers that
2443 are not included in the DLL. When an application or a DLL is linked,
2444 an import library may be generated, which will need to be used for all
2445 future DLLs that depend on the symbols in the application or DLL.
2447 Suppose you are building two dynamic-load modules, B and C, which should
2448 share another block of code A. On \UNIX{}, you would \emph{not} pass
2449 \file{A.a} to the linker for \file{B.so} and \file{C.so}; that would
2450 cause it to be included twice, so that B and C would each have their
2451 own copy. In Windows, building \file{A.dll} will also build
2452 \file{A.lib}. You \emph{do} pass \file{A.lib} to the linker for B and
2453 C. \file{A.lib} does not contain code; it just contains information
2454 which will be used at runtime to access A's code.
2456 In Windows, using an import library is sort of like using \samp{import
2457 spam}; it gives you access to spam's names, but does not create a
2458 separate copy. On \UNIX{}, linking with a library is more like
2459 \samp{from spam import *}; it does create a separate copy.
2462 \section{Using DLLs in Practice \label{win-dlls}}
2463 \sectionauthor{Chris Phoenix}{cphoenix@best.com}
2465 Windows Python is built in Microsoft Visual \Cpp{}; using other
2466 compilers may or may not work (though Borland seems to). The rest of
2467 this section is MSV\Cpp{} specific.
2469 When creating DLLs in Windows, you must pass \file{python15.lib} to
2470 the linker. To build two DLLs, spam and ni (which uses C functions
2471 found in spam), you could use these commands:
2473 \begin{verbatim}
2474 cl /LD /I/python/include spam.c ../libs/python15.lib
2475 cl /LD /I/python/include ni.c spam.lib ../libs/python15.lib
2476 \end{verbatim}
2478 The first command created three files: \file{spam.obj},
2479 \file{spam.dll} and \file{spam.lib}. \file{Spam.dll} does not contain
2480 any Python functions (such as \cfunction{PyArg_ParseTuple()}), but it
2481 does know how to find the Python code thanks to \file{python15.lib}.
2483 The second command created \file{ni.dll} (and \file{.obj} and
2484 \file{.lib}), which knows how to find the necessary functions from
2485 spam, and also from the Python executable.
2487 Not every identifier is exported to the lookup table. If you want any
2488 other modules (including Python) to be able to see your identifiers,
2489 you have to say \samp{_declspec(dllexport)}, as in \samp{void
2490 _declspec(dllexport) initspam(void)} or \samp{PyObject
2491 _declspec(dllexport) *NiGetSpamData(void)}.
2493 Developer Studio will throw in a lot of import libraries that you do
2494 not really need, adding about 100K to your executable. To get rid of
2495 them, use the Project Settings dialog, Link tab, to specify
2496 \emph{ignore default libraries}. Add the correct
2497 \file{msvcrt\var{xx}.lib} to the list of libraries.
2500 \chapter{Embedding Python in Another Application
2501 \label{embedding}}
2503 Embedding Python is similar to extending it, but not quite. The
2504 difference is that when you extend Python, the main program of the
2505 application is still the Python interpreter, while if you embed
2506 Python, the main program may have nothing to do with Python ---
2507 instead, some parts of the application occasionally call the Python
2508 interpreter to run some Python code.
2510 So if you are embedding Python, you are providing your own main
2511 program. One of the things this main program has to do is initialize
2512 the Python interpreter. At the very least, you have to call the
2513 function \cfunction{Py_Initialize()} (on MacOS, call
2514 \cfunction{PyMac_Initialize()} instead). There are optional calls to
2515 pass command line arguments to Python. Then later you can call the
2516 interpreter from any part of the application.
2518 There are several different ways to call the interpreter: you can pass
2519 a string containing Python statements to
2520 \cfunction{PyRun_SimpleString()}, or you can pass a stdio file pointer
2521 and a file name (for identification in error messages only) to
2522 \cfunction{PyRun_SimpleFile()}. You can also call the lower-level
2523 operations described in the previous chapters to construct and use
2524 Python objects.
2526 A simple demo of embedding Python can be found in the directory
2527 \file{Demo/embed/} of the source distribution.
2530 \section{Embedding Python in \Cpp{}
2531 \label{embeddingInCplusplus}}
2533 It is also possible to embed Python in a \Cpp{} program; precisely how this
2534 is done will depend on the details of the \Cpp{} system used; in general you
2535 will need to write the main program in \Cpp{}, and use the \Cpp{} compiler
2536 to compile and link your program. There is no need to recompile Python
2537 itself using \Cpp{}.
2540 \section{Linking Requirements
2541 \label{link-reqs}}
2543 While the \program{configure} script shipped with the Python sources
2544 will correctly build Python to export the symbols needed by
2545 dynamically linked extensions, this is not automatically inherited by
2546 applications which embed the Python library statically, at least on
2547 \UNIX. This is an issue when the application is linked to the static
2548 runtime library (\file{libpython.a}) and needs to load dynamic
2549 extensions (implemented as \file{.so} files).
2551 The problem is that some entry points are defined by the Python
2552 runtime solely for extension modules to use. If the embedding
2553 application does not use any of these entry points, some linkers will
2554 not include those entries in the symbol table of the finished
2555 executable. Some additional options are needed to inform the linker
2556 not to remove these symbols.
2558 Determining the right options to use for any given platform can be
2559 quite difficult, but fortunately the Python configuration already has
2560 those values. To retrieve them from an installed Python interpreter,
2561 start an interactive interpreter and have a short session like this:
2563 \begin{verbatim}
2564 >>> import distutils.sysconfig
2565 >>> distutils.sysconfig.get_config_var('LINKFORSHARED')
2566 '-Xlinker -export-dynamic'
2567 \end{verbatim}
2568 \refstmodindex{distutils.sysconfig}
2570 The contents of the string presented will be the options that should
2571 be used. If the string is empty, there's no need to add any
2572 additional options. The \constant{LINKFORSHARED} definition
2573 corresponds to the variable of the same name in Python's top-level
2574 \file{Makefile}.
2577 \appendix
2578 \chapter{Reporting Bugs}
2579 \input{reportingbugs}
2581 \chapter{History and License}
2582 \input{license}
2584 \end{document}