struct.pack has become picky about h (short) and H (unsigned short).
[python/dscho.git] / Doc / ext / ext.tex
blobc29062c898781a5f6558b24e4ab5453dacf15940
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}
22 %begin{latexonly}
23 \vspace{1in}
24 %end{latexonly}
25 \strong{\large Acknowledgements}
27 % XXX This needs to be checked and updated manually before each
28 % release.
30 The following people have contributed sections to this document: Jim
31 Fulton, Konrad Hinsen, Chris Phoenix, and Neil Schemenauer.
33 \begin{abstract}
35 \noindent
36 Python is an interpreted, object-oriented programming language. This
37 document describes how to write modules in C or \Cpp{} to extend the
38 Python interpreter with new modules. Those modules can define new
39 functions but also new object types and their methods. The document
40 also describes how to embed the Python interpreter in another
41 application, for use as an extension language. Finally, it shows how
42 to compile and link extension modules so that they can be loaded
43 dynamically (at run time) into the interpreter, if the underlying
44 operating system supports this feature.
46 This document assumes basic knowledge about Python. For an informal
47 introduction to the language, see the
48 \citetitle[../tut/tut.html]{Python Tutorial}. The
49 \citetitle[../ref/ref.html]{Python Reference Manual} gives a more
50 formal definition of the language. The
51 \citetitle[../lib/lib.html]{Python Library Reference} documents the
52 existing object types, functions and modules (both built-in and
53 written in Python) that give the language its wide application range.
55 For a detailed description of the whole Python/C API, see the separate
56 \citetitle[../api/api.html]{Python/C API Reference Manual}.
58 \end{abstract}
60 \tableofcontents
63 \chapter{Extending Python with C or \Cpp{} \label{intro}}
66 It is quite easy to add new built-in modules to Python, if you know
67 how to program in C. Such \dfn{extension modules} can do two things
68 that can't be done directly in Python: they can implement new built-in
69 object types, and they can call C library functions and system calls.
71 To support extensions, the Python API (Application Programmers
72 Interface) defines a set of functions, macros and variables that
73 provide access to most aspects of the Python run-time system. The
74 Python API is incorporated in a C source file by including the header
75 \code{"Python.h"}.
77 The compilation of an extension module depends on its intended use as
78 well as on your system setup; details are given in later chapters.
81 \section{A Simple Example
82 \label{simpleExample}}
84 Let's create an extension module called \samp{spam} (the favorite food
85 of Monty Python fans...) and let's say we want to create a Python
86 interface to the C library function \cfunction{system()}.\footnote{An
87 interface for this function already exists in the standard module
88 \module{os} --- it was chosen as a simple and straightfoward example.}
89 This function takes a null-terminated character string as argument and
90 returns an integer. We want this function to be callable from Python
91 as follows:
93 \begin{verbatim}
94 >>> import spam
95 >>> status = spam.system("ls -l")
96 \end{verbatim}
98 Begin by creating a file \file{spammodule.c}. (Historically, if a
99 module is called \samp{spam}, the C file containing its implementation
100 is called \file{spammodule.c}; if the module name is very long, like
101 \samp{spammify}, the module name can be just \file{spammify.c}.)
103 The first line of our file can be:
105 \begin{verbatim}
106 #include <Python.h>
107 \end{verbatim}
109 which pulls in the Python API (you can add a comment describing the
110 purpose of the module and a copyright notice if you like).
112 All user-visible symbols defined by \code{"Python.h"} have a prefix of
113 \samp{Py} or \samp{PY}, except those defined in standard header files.
114 For convenience, and since they are used extensively by the Python
115 interpreter, \code{"Python.h"} includes a few standard header files:
116 \code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and
117 \code{<stdlib.h>}. If the latter header file does not exist on your
118 system, it declares the functions \cfunction{malloc()},
119 \cfunction{free()} and \cfunction{realloc()} directly.
121 The next thing we add to our module file is the C function that will
122 be called when the Python expression \samp{spam.system(\var{string})}
123 is evaluated (we'll see shortly how it ends up being called):
125 \begin{verbatim}
126 static PyObject *
127 spam_system(self, args)
128 PyObject *self;
129 PyObject *args;
131 char *command;
132 int sts;
134 if (!PyArg_ParseTuple(args, "s", &command))
135 return NULL;
136 sts = system(command);
137 return Py_BuildValue("i", sts);
139 \end{verbatim}
141 There is a straightforward translation from the argument list in
142 Python (e.g.\ the single expression \code{"ls -l"}) to the arguments
143 passed to the C function. The C function always has two arguments,
144 conventionally named \var{self} and \var{args}.
146 The \var{self} argument is only used when the C function implements a
147 built-in method, not a function. In the example, \var{self} will
148 always be a \NULL{} pointer, since we are defining a function, not a
149 method. (This is done so that the interpreter doesn't have to
150 understand two different types of C functions.)
152 The \var{args} argument will be a pointer to a Python tuple object
153 containing the arguments. Each item of the tuple corresponds to an
154 argument in the call's argument list. The arguments are Python
155 objects --- in order to do anything with them in our C function we have
156 to convert them to C values. The function \cfunction{PyArg_ParseTuple()}
157 in the Python API checks the argument types and converts them to C
158 values. It uses a template string to determine the required types of
159 the arguments as well as the types of the C variables into which to
160 store the converted values. More about this later.
162 \cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have
163 the right type and its components have been stored in the variables
164 whose addresses are passed. It returns false (zero) if an invalid
165 argument list was passed. In the latter case it also raises an
166 appropriate exception so the calling function can return
167 \NULL{} immediately (as we saw in the example).
170 \section{Intermezzo: Errors and Exceptions
171 \label{errors}}
173 An important convention throughout the Python interpreter is the
174 following: when a function fails, it should set an exception condition
175 and return an error value (usually a \NULL{} pointer). Exceptions
176 are stored in a static global variable inside the interpreter; if this
177 variable is \NULL{} no exception has occurred. A second global
178 variable stores the ``associated value'' of the exception (the second
179 argument to \keyword{raise}). A third variable contains the stack
180 traceback in case the error originated in Python code. These three
181 variables are the C equivalents of the Python variables
182 \code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see
183 the section on module \module{sys} in the
184 \citetitle[../lib/lib.html]{Python Library Reference}). It is
185 important to know about them to understand how errors are passed
186 around.
188 The Python API defines a number of functions to set various types of
189 exceptions.
191 The most common one is \cfunction{PyErr_SetString()}. Its arguments
192 are an exception object and a C string. The exception object is
193 usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The
194 C string indicates the cause of the error and is converted to a
195 Python string object and stored as the ``associated value'' of the
196 exception.
198 Another useful function is \cfunction{PyErr_SetFromErrno()}, which only
199 takes an exception argument and constructs the associated value by
200 inspection of the global variable \cdata{errno}. The most
201 general function is \cfunction{PyErr_SetObject()}, which takes two object
202 arguments, the exception and its associated value. You don't need to
203 \cfunction{Py_INCREF()} the objects passed to any of these functions.
205 You can test non-destructively whether an exception has been set with
206 \cfunction{PyErr_Occurred()}. This returns the current exception object,
207 or \NULL{} if no exception has occurred. You normally don't need
208 to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a
209 function call, since you should be able to tell from the return value.
211 When a function \var{f} that calls another function \var{g} detects
212 that the latter fails, \var{f} should itself return an error value
213 (e.g.\ \NULL{} or \code{-1}). It should \emph{not} call one of the
214 \cfunction{PyErr_*()} functions --- one has already been called by \var{g}.
215 \var{f}'s caller is then supposed to also return an error indication
216 to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()},
217 and so on --- the most detailed cause of the error was already
218 reported by the function that first detected it. Once the error
219 reaches the Python interpreter's main loop, this aborts the currently
220 executing Python code and tries to find an exception handler specified
221 by the Python programmer.
223 (There are situations where a module can actually give a more detailed
224 error message by calling another \cfunction{PyErr_*()} function, and in
225 such cases it is fine to do so. As a general rule, however, this is
226 not necessary, and can cause information about the cause of the error
227 to be lost: most operations can fail for a variety of reasons.)
229 To ignore an exception set by a function call that failed, the exception
230 condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}.
231 The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't
232 want to pass the error on to the interpreter but wants to handle it
233 completely by itself (e.g.\ by trying something else or pretending
234 nothing happened).
236 Every failing \cfunction{malloc()} call must be turned into an
237 exception --- the direct caller of \cfunction{malloc()} (or
238 \cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and
239 return a failure indicator itself. All the object-creating functions
240 (for example, \cfunction{PyInt_FromLong()}) already do this, so this
241 note is only relevant to those who call \cfunction{malloc()} directly.
243 Also note that, with the important exception of
244 \cfunction{PyArg_ParseTuple()} and friends, functions that return an
245 integer status usually return a positive value or zero for success and
246 \code{-1} for failure, like \UNIX{} system calls.
248 Finally, be careful to clean up garbage (by making
249 \cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects
250 you have already created) when you return an error indicator!
252 The choice of which exception to raise is entirely yours. There are
253 predeclared C objects corresponding to all built-in Python exceptions,
254 e.g.\ \cdata{PyExc_ZeroDivisionError}, which you can use directly. Of
255 course, you should choose exceptions wisely --- don't use
256 \cdata{PyExc_TypeError} to mean that a file couldn't be opened (that
257 should probably be \cdata{PyExc_IOError}). If something's wrong with
258 the argument list, the \cfunction{PyArg_ParseTuple()} function usually
259 raises \cdata{PyExc_TypeError}. If you have an argument whose value
260 must be in a particular range or must satisfy other conditions,
261 \cdata{PyExc_ValueError} is appropriate.
263 You can also define a new exception that is unique to your module.
264 For this, you usually declare a static object variable at the
265 beginning of your file, e.g.
267 \begin{verbatim}
268 static PyObject *SpamError;
269 \end{verbatim}
271 and initialize it in your module's initialization function
272 (\cfunction{initspam()}) with an exception object, e.g.\ (leaving out
273 the error checking for now):
275 \begin{verbatim}
276 void
277 initspam()
279 PyObject *m, *d;
281 m = Py_InitModule("spam", SpamMethods);
282 d = PyModule_GetDict(m);
283 SpamError = PyErr_NewException("spam.error", NULL, NULL);
284 PyDict_SetItemString(d, "error", SpamError);
286 \end{verbatim}
288 Note that the Python name for the exception object is
289 \exception{spam.error}. The \cfunction{PyErr_NewException()} function
290 may create either a string or class, depending on whether the
291 \programopt{-X} flag was passed to the interpreter. If
292 \programopt{-X} was used, \cdata{SpamError} will be a string object,
293 otherwise it will be a class object with the base class being
294 \exception{Exception}, described in the
295 \citetitle[../lib/lib.html]{Python Library Reference} under ``Built-in
296 Exceptions.''
299 \section{Back to the Example
300 \label{backToExample}}
302 Going back to our example function, you should now be able to
303 understand this statement:
305 \begin{verbatim}
306 if (!PyArg_ParseTuple(args, "s", &command))
307 return NULL;
308 \end{verbatim}
310 It returns \NULL{} (the error indicator for functions returning
311 object pointers) if an error is detected in the argument list, relying
312 on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the
313 string value of the argument has been copied to the local variable
314 \cdata{command}. This is a pointer assignment and you are not supposed
315 to modify the string to which it points (so in Standard C, the variable
316 \cdata{command} should properly be declared as \samp{const char
317 *command}).
319 The next statement is a call to the \UNIX{} function
320 \cfunction{system()}, passing it the string we just got from
321 \cfunction{PyArg_ParseTuple()}:
323 \begin{verbatim}
324 sts = system(command);
325 \end{verbatim}
327 Our \function{spam.system()} function must return the value of
328 \cdata{sts} as a Python object. This is done using the function
329 \cfunction{Py_BuildValue()}, which is something like the inverse of
330 \cfunction{PyArg_ParseTuple()}: it takes a format string and an
331 arbitrary number of C values, and returns a new Python object.
332 More info on \cfunction{Py_BuildValue()} is given later.
334 \begin{verbatim}
335 return Py_BuildValue("i", sts);
336 \end{verbatim}
338 In this case, it will return an integer object. (Yes, even integers
339 are objects on the heap in Python!)
341 If you have a C function that returns no useful argument (a function
342 returning \ctype{void}), the corresponding Python function must return
343 \code{None}. You need this idiom to do so:
345 \begin{verbatim}
346 Py_INCREF(Py_None);
347 return Py_None;
348 \end{verbatim}
350 \cdata{Py_None} is the C name for the special Python object
351 \code{None}. It is a genuine Python object rather than a \NULL{}
352 pointer, which means ``error'' in most contexts, as we have seen.
355 \section{The Module's Method Table and Initialization Function
356 \label{methodTable}}
358 I promised to show how \cfunction{spam_system()} is called from Python
359 programs. First, we need to list its name and address in a ``method
360 table'':
362 \begin{verbatim}
363 static PyMethodDef SpamMethods[] = {
365 {"system", spam_system, METH_VARARGS},
367 {NULL, NULL} /* Sentinel */
369 \end{verbatim}
371 Note the third entry (\samp{METH_VARARGS}). This is a flag telling
372 the interpreter the calling convention to be used for the C
373 function. It should normally always be \samp{METH_VARARGS} or
374 \samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an
375 obsolete variant of \cfunction{PyArg_ParseTuple()} is used.
377 When using only \samp{METH_VARARGS}, the function should expect
378 the Python-level parameters to be passed in as a tuple acceptable for
379 parsing via \cfunction{PyArg_ParseTuple()}; more information on this
380 function is provided below.
382 The \constant{METH_KEYWORDS} bit may be set in the third field if
383 keyword arguments should be passed to the function. In this case, the
384 C function should accept a third \samp{PyObject *} parameter which
385 will be a dictionary of keywords. Use
386 \cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to
387 such a function.
389 The method table must be passed to the interpreter in the module's
390 initialization function. The initialization function must be named
391 \cfunction{init\var{name}()}, where \var{name} is the name of the
392 module, and should be the only non-\keyword{static} item defined in
393 the module file:
395 \begin{verbatim}
396 void
397 initspam()
399 (void) Py_InitModule("spam", SpamMethods);
401 \end{verbatim}
403 Note that for \Cpp, this method must be declared \code{extern "C"}.
405 When the Python program imports module \module{spam} for the first
406 time, \cfunction{initspam()} is called. (See below for comments about
407 embedding Python.) It calls
408 \cfunction{Py_InitModule()}, which creates a ``module object'' (which
409 is inserted in the dictionary \code{sys.modules} under the key
410 \code{"spam"}), and inserts built-in function objects into the newly
411 created module based upon the table (an array of \ctype{PyMethodDef}
412 structures) that was passed as its second argument.
413 \cfunction{Py_InitModule()} returns a pointer to the module object
414 that it creates (which is unused here). It aborts with a fatal error
415 if the module could not be initialized satisfactorily, so the caller
416 doesn't need to check for errors.
418 When embedding Python, the \cfunction{initspam()} function is not
419 called automatically unless there's an entry in the
420 \cdata{_PyImport_Inittab} table. The easiest way to handle this is to
421 statically initialize your statically-linked modules by directly
422 calling \cfunction{initspam()} after the call to
423 \cfunction{Py_Initialize()} or \cfunction{PyMac_Initialize()}:
425 \begin{verbatim}
426 int main(int argc, char **argv)
428 /* Pass argv[0] to the Python interpreter */
429 Py_SetProgramName(argv[0]);
431 /* Initialize the Python interpreter. Required. */
432 Py_Initialize();
434 /* Add a static module */
435 initspam();
436 \end{verbatim}
438 An example may be found in the file \file{Demo/embed/demo.c} in the
439 Python source distribution.
441 \strong{Note:} Removing entries from \code{sys.modules} or importing
442 compiled modules into multiple interpreters within a process (or
443 following a \cfunction{fork()} without an intervening
444 \cfunction{exec()}) can create problems for some extension modules.
445 Extension module authors should exercise caution when initializing
446 internal data structures.
447 Note also that the \function{reload()} function can be used with
448 extension modules, and will call the module initialization function
449 (\cfunction{initspam()} in the example), but will not load the module
450 again if it was loaded from a dynamically loadable object file
451 (\file{.so} on \UNIX, \file{.dll} on Windows).
453 A more substantial example module is included in the Python source
454 distribution as \file{Modules/xxmodule.c}. This file may be used as a
455 template or simply read as an example. The \program{modulator.py}
456 script included in the source distribution or Windows install provides
457 a simple graphical user interface for declaring the functions and
458 objects which a module should implement, and can generate a template
459 which can be filled in. The script lives in the
460 \file{Tools/modulator/} directory; see the \file{README} file there
461 for more information.
464 \section{Compilation and Linkage
465 \label{compilation}}
467 There are two more things to do before you can use your new extension:
468 compiling and linking it with the Python system. If you use dynamic
469 loading, the details depend on the style of dynamic loading your
470 system uses; see the chapters about building extension modules on
471 \UNIX{} (chapter \ref{building-on-unix}) and Windows (chapter
472 \ref{building-on-windows}) for more information about this.
473 % XXX Add information about MacOS
475 If you can't use dynamic loading, or if you want to make your module a
476 permanent part of the Python interpreter, you will have to change the
477 configuration setup and rebuild the interpreter. Luckily, this is
478 very simple: just place your file (\file{spammodule.c} for example) in
479 the \file{Modules/} directory of an unpacked source distribution, add
480 a line to the file \file{Modules/Setup.local} describing your file:
482 \begin{verbatim}
483 spam spammodule.o
484 \end{verbatim}
486 and rebuild the interpreter by running \program{make} in the toplevel
487 directory. You can also run \program{make} in the \file{Modules/}
488 subdirectory, but then you must first rebuild \file{Makefile}
489 there by running `\program{make} Makefile'. (This is necessary each
490 time you change the \file{Setup} file.)
492 If your module requires additional libraries to link with, these can
493 be listed on the line in the configuration file as well, for instance:
495 \begin{verbatim}
496 spam spammodule.o -lX11
497 \end{verbatim}
499 \section{Calling Python Functions from C
500 \label{callingPython}}
502 So far we have concentrated on making C functions callable from
503 Python. The reverse is also useful: calling Python functions from C.
504 This is especially the case for libraries that support so-called
505 ``callback'' functions. If a C interface makes use of callbacks, the
506 equivalent Python often needs to provide a callback mechanism to the
507 Python programmer; the implementation will require calling the Python
508 callback functions from a C callback. Other uses are also imaginable.
510 Fortunately, the Python interpreter is easily called recursively, and
511 there is a standard interface to call a Python function. (I won't
512 dwell on how to call the Python parser with a particular string as
513 input --- if you're interested, have a look at the implementation of
514 the \programopt{-c} command line option in \file{Python/pythonmain.c}
515 from the Python source code.)
517 Calling a Python function is easy. First, the Python program must
518 somehow pass you the Python function object. You should provide a
519 function (or some other interface) to do this. When this function is
520 called, save a pointer to the Python function object (be careful to
521 \cfunction{Py_INCREF()} it!) in a global variable --- or wherever you
522 see fit. For example, the following function might be part of a module
523 definition:
525 \begin{verbatim}
526 static PyObject *my_callback = NULL;
528 static PyObject *
529 my_set_callback(dummy, args)
530 PyObject *dummy, *args;
532 PyObject *result = NULL;
533 PyObject *temp;
535 if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
536 if (!PyCallable_Check(temp)) {
537 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
538 return NULL;
540 Py_XINCREF(temp); /* Add a reference to new callback */
541 Py_XDECREF(my_callback); /* Dispose of previous callback */
542 my_callback = temp; /* Remember new callback */
543 /* Boilerplate to return "None" */
544 Py_INCREF(Py_None);
545 result = Py_None;
547 return result;
549 \end{verbatim}
551 This function must be registered with the interpreter using the
552 \constant{METH_VARARGS} flag; this is described in section
553 \ref{methodTable}, ``The Module's Method Table and Initialization
554 Function.'' The \cfunction{PyArg_ParseTuple()} function and its
555 arguments are documented in section \ref{parseTuple}, ``Format Strings
556 for \cfunction{PyArg_ParseTuple()}.''
558 The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()}
559 increment/decrement the reference count of an object and are safe in
560 the presence of \NULL{} pointers (but note that \var{temp} will not be
561 \NULL{} in this context). More info on them in section
562 \ref{refcounts}, ``Reference Counts.''
564 Later, when it is time to call the function, you call the C function
565 \cfunction{PyEval_CallObject()}. This function has two arguments, both
566 pointers to arbitrary Python objects: the Python function, and the
567 argument list. The argument list must always be a tuple object, whose
568 length is the number of arguments. To call the Python function with
569 no arguments, pass an empty tuple; to call it with one argument, pass
570 a singleton tuple. \cfunction{Py_BuildValue()} returns a tuple when its
571 format string consists of zero or more format codes between
572 parentheses. For example:
574 \begin{verbatim}
575 int arg;
576 PyObject *arglist;
577 PyObject *result;
579 arg = 123;
581 /* Time to call the callback */
582 arglist = Py_BuildValue("(i)", arg);
583 result = PyEval_CallObject(my_callback, arglist);
584 Py_DECREF(arglist);
585 \end{verbatim}
587 \cfunction{PyEval_CallObject()} returns a Python object pointer: this is
588 the return value of the Python function. \cfunction{PyEval_CallObject()} is
589 ``reference-count-neutral'' with respect to its arguments. In the
590 example a new tuple was created to serve as the argument list, which
591 is \cfunction{Py_DECREF()}-ed immediately after the call.
593 The return value of \cfunction{PyEval_CallObject()} is ``new'': either it
594 is a brand new object, or it is an existing object whose reference
595 count has been incremented. So, unless you want to save it in a
596 global variable, you should somehow \cfunction{Py_DECREF()} the result,
597 even (especially!) if you are not interested in its value.
599 Before you do this, however, it is important to check that the return
600 value isn't \NULL{}. If it is, the Python function terminated by
601 raising an exception. If the C code that called
602 \cfunction{PyEval_CallObject()} is called from Python, it should now
603 return an error indication to its Python caller, so the interpreter
604 can print a stack trace, or the calling Python code can handle the
605 exception. If this is not possible or desirable, the exception should
606 be cleared by calling \cfunction{PyErr_Clear()}. For example:
608 \begin{verbatim}
609 if (result == NULL)
610 return NULL; /* Pass error back */
611 ...use result...
612 Py_DECREF(result);
613 \end{verbatim}
615 Depending on the desired interface to the Python callback function,
616 you may also have to provide an argument list to
617 \cfunction{PyEval_CallObject()}. In some cases the argument list is
618 also provided by the Python program, through the same interface that
619 specified the callback function. It can then be saved and used in the
620 same manner as the function object. In other cases, you may have to
621 construct a new tuple to pass as the argument list. The simplest way
622 to do this is to call \cfunction{Py_BuildValue()}. For example, if
623 you want to pass an integral event code, you might use the following
624 code:
626 \begin{verbatim}
627 PyObject *arglist;
629 arglist = Py_BuildValue("(l)", eventcode);
630 result = PyEval_CallObject(my_callback, arglist);
631 Py_DECREF(arglist);
632 if (result == NULL)
633 return NULL; /* Pass error back */
634 /* Here maybe use the result */
635 Py_DECREF(result);
636 \end{verbatim}
638 Note the placement of \samp{Py_DECREF(arglist)} immediately after the
639 call, before the error check! Also note that strictly spoken this
640 code is not complete: \cfunction{Py_BuildValue()} may run out of
641 memory, and this should be checked.
644 \section{Format Strings for \cfunction{PyArg_ParseTuple()}
645 \label{parseTuple}}
647 The \cfunction{PyArg_ParseTuple()} function is declared as follows:
649 \begin{verbatim}
650 int PyArg_ParseTuple(PyObject *arg, char *format, ...);
651 \end{verbatim}
653 The \var{arg} argument must be a tuple object containing an argument
654 list passed from Python to a C function. The \var{format} argument
655 must be a format string, whose syntax is explained below. The
656 remaining arguments must be addresses of variables whose type is
657 determined by the format string. For the conversion to succeed, the
658 \var{arg} object must match the format and the format must be
659 exhausted.
661 Note that while \cfunction{PyArg_ParseTuple()} checks that the Python
662 arguments have the required types, it cannot check the validity of the
663 addresses of C variables passed to the call: if you make mistakes
664 there, your code will probably crash or at least overwrite random bits
665 in memory. So be careful!
667 A format string consists of zero or more ``format units''. A format
668 unit describes one Python object; it is usually a single character or
669 a parenthesized sequence of format units. With a few exceptions, a
670 format unit that is not a parenthesized sequence normally corresponds
671 to a single address argument to \cfunction{PyArg_ParseTuple()}. In the
672 following description, the quoted form is the format unit; the entry
673 in (round) parentheses is the Python object type that matches the
674 format unit; and the entry in [square] brackets is the type of the C
675 variable(s) whose address should be passed. (Use the \samp{\&}
676 operator to pass a variable's address.)
678 Note that any Python object references which are provided to the
679 caller are \emph{borrowed} references; do not decrement their
680 reference count!
682 \begin{description}
684 \item[\samp{s} (string or Unicode object) {[char *]}]
685 Convert a Python string or Unicode object to a C pointer to a
686 character string. You must not provide storage for the string
687 itself; a pointer to an existing string is stored into the character
688 pointer variable whose address you pass. The C string is
689 null-terminated. The Python string must not contain embedded null
690 bytes; if it does, a \exception{TypeError} exception is raised.
691 Unicode objects are converted to C strings using the default
692 encoding. If this conversion fails, an \exception{UnicodeError} is
693 raised.
695 \item[\samp{s\#} (string, Unicode or any read buffer compatible object)
696 {[char *, int]}]
697 This variant on \samp{s} stores into two C variables, the first one a
698 pointer to a character string, the second one its length. In this
699 case the Python string may contain embedded null bytes. Unicode
700 objects pass back a pointer to the default encoded string version of the
701 object if such a conversion is possible. All other read buffer
702 compatible objects pass back a reference to the raw internal data
703 representation.
705 \item[\samp{z} (string or \code{None}) {[char *]}]
706 Like \samp{s}, but the Python object may also be \code{None}, in which
707 case the C pointer is set to \NULL{}.
709 \item[\samp{z\#} (string or \code{None} or any read buffer compatible object)
710 {[char *, int]}]
711 This is to \samp{s\#} as \samp{z} is to \samp{s}.
713 \item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
714 Convert a Python Unicode object to a C pointer to a null-terminated
715 buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need
716 to provide storage for the Unicode data buffer; a pointer to the
717 existing Unicode data is stored into the Py_UNICODE pointer variable whose
718 address you pass.
720 \item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
721 This variant on \samp{u} stores into two C variables, the first one
722 a pointer to a Unicode data buffer, the second one its length.
724 \item[\samp{es} (string, Unicode object or character buffer compatible
725 object) {[const char *encoding, char **buffer]}]
726 This variant on \samp{s} is used for encoding Unicode and objects
727 convertible to Unicode into a character buffer. It only works for
728 encoded data without embedded \NULL{} bytes.
730 The variant reads one C variable and stores into two C variables, the
731 first one a pointer to an encoding name string (\var{encoding}), the
732 second a pointer to a pointer to a character buffer (\var{**buffer},
733 the buffer used for storing the encoded data) and the third one a
734 pointer to an integer (\var{*buffer_length}, the buffer length).
736 The encoding name must map to a registered codec. If set to \NULL{},
737 the default encoding is used.
739 \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
740 size using \cfunction{PyMem_NEW()}, copy the encoded data into this
741 buffer and adjust \var{*buffer} to reference the newly allocated
742 storage. The caller is responsible for calling
743 \cfunction{PyMem_Free()} to free the allocated buffer after usage.
745 \item[\samp{es\#} (string, Unicode object or character buffer compatible
746 object) {[const char *encoding, char **buffer, int *buffer_length]}]
747 This variant on \samp{s\#} is used for encoding Unicode and objects
748 convertible to Unicode into a character buffer. It reads one C
749 variable and stores into two C variables, the first one a pointer to
750 an encoding name string (\var{encoding}), the second a pointer to a
751 pointer to a character buffer (\var{**buffer}, the buffer used for
752 storing the encoded data) and the third one a pointer to an integer
753 (\var{*buffer_length}, the buffer length).
755 The encoding name must map to a registered codec. If set to \NULL{},
756 the default encoding is used.
758 There are two modes of operation:
760 If \var{*buffer} points a \NULL{} pointer,
761 \cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
762 size using \cfunction{PyMem_NEW()}, copy the encoded data into this
763 buffer and adjust \var{*buffer} to reference the newly allocated
764 storage. The caller is responsible for calling
765 \cfunction{PyMem_Free()} to free the allocated buffer after usage.
767 If \var{*buffer} points to a non-\NULL{} pointer (an already allocated
768 buffer), \cfunction{PyArg_ParseTuple()} will use this location as
769 buffer and interpret \var{*buffer_length} as buffer size. It will then
770 copy the encoded data into the buffer and 0-terminate it. Buffer
771 overflow is signalled with an exception.
773 In both cases, \var{*buffer_length} is set to the length of the
774 encoded data without the trailing 0-byte.
776 \item[\samp{b} (integer) {[char]}]
777 Convert a Python integer to a tiny int, stored in a C \ctype{char}.
779 \item[\samp{h} (integer) {[short int]}]
780 Convert a Python integer to a C \ctype{short int}.
782 \item[\samp{i} (integer) {[int]}]
783 Convert a Python integer to a plain C \ctype{int}.
785 \item[\samp{l} (integer) {[long int]}]
786 Convert a Python integer to a C \ctype{long int}.
788 \item[\samp{c} (string of length 1) {[char]}]
789 Convert a Python character, represented as a string of length 1, to a
790 C \ctype{char}.
792 \item[\samp{f} (float) {[float]}]
793 Convert a Python floating point number to a C \ctype{float}.
795 \item[\samp{d} (float) {[double]}]
796 Convert a Python floating point number to a C \ctype{double}.
798 \item[\samp{D} (complex) {[Py_complex]}]
799 Convert a Python complex number to a C \ctype{Py_complex} structure.
801 \item[\samp{O} (object) {[PyObject *]}]
802 Store a Python object (without any conversion) in a C object pointer.
803 The C program thus receives the actual object that was passed. The
804 object's reference count is not increased. The pointer stored is not
805 \NULL{}.
807 \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
808 Store a Python object in a C object pointer. This is similar to
809 \samp{O}, but takes two C arguments: the first is the address of a
810 Python type object, the second is the address of the C variable (of
811 type \ctype{PyObject *}) into which the object pointer is stored.
812 If the Python object does not have the required type,
813 \exception{TypeError} is raised.
815 \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
816 Convert a Python object to a C variable through a \var{converter}
817 function. This takes two arguments: the first is a function, the
818 second is the address of a C variable (of arbitrary type), converted
819 to \ctype{void *}. The \var{converter} function in turn is called as
820 follows:
822 \var{status}\code{ = }\var{converter}\code{(}\var{object}, \var{address}\code{);}
824 where \var{object} is the Python object to be converted and
825 \var{address} is the \ctype{void *} argument that was passed to
826 \cfunction{PyArg_ConvertTuple()}. The returned \var{status} should be
827 \code{1} for a successful conversion and \code{0} if the conversion
828 has failed. When the conversion fails, the \var{converter} function
829 should raise an exception.
831 \item[\samp{S} (string) {[PyStringObject *]}]
832 Like \samp{O} but requires that the Python object is a string object.
833 Raises \exception{TypeError} if the object is not a string object.
834 The C variable may also be declared as \ctype{PyObject *}.
836 \item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
837 Like \samp{O} but requires that the Python object is a Unicode object.
838 Raises \exception{TypeError} if the object is not a Unicode object.
839 The C variable may also be declared as \ctype{PyObject *}.
841 \item[\samp{t\#} (read-only character buffer) {[char *, int]}]
842 Like \samp{s\#}, but accepts any object which implements the read-only
843 buffer interface. The \ctype{char *} variable is set to point to the
844 first byte of the buffer, and the \ctype{int} is set to the length of
845 the buffer. Only single-segment buffer objects are accepted;
846 \exception{TypeError} is raised for all others.
848 \item[\samp{w} (read-write character buffer) {[char *]}]
849 Similar to \samp{s}, but accepts any object which implements the
850 read-write buffer interface. The caller must determine the length of
851 the buffer by other means, or use \samp{w\#} instead. Only
852 single-segment buffer objects are accepted; \exception{TypeError} is
853 raised for all others.
855 \item[\samp{w\#} (read-write character buffer) {[char *, int]}]
856 Like \samp{s\#}, but accepts any object which implements the
857 read-write buffer interface. The \ctype{char *} variable is set to
858 point to the first byte of the buffer, and the \ctype{int} is set to
859 the length of the buffer. Only single-segment buffer objects are
860 accepted; \exception{TypeError} is raised for all others.
862 \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
863 The object must be a Python sequence whose length is the number of
864 format units in \var{items}. The C arguments must correspond to the
865 individual format units in \var{items}. Format units for sequences
866 may be nested.
868 \strong{Note:} Prior to Python version 1.5.2, this format specifier
869 only accepted a tuple containing the individual parameters, not an
870 arbitrary sequence. Code which previously caused
871 \exception{TypeError} to be raised here may now proceed without an
872 exception. This is not expected to be a problem for existing code.
874 \end{description}
876 It is possible to pass Python long integers where integers are
877 requested; however no proper range checking is done --- the most
878 significant bits are silently truncated when the receiving field is
879 too small to receive the value (actually, the semantics are inherited
880 from downcasts in C --- your mileage may vary).
882 A few other characters have a meaning in a format string. These may
883 not occur inside nested parentheses. They are:
885 \begin{description}
887 \item[\samp{|}]
888 Indicates that the remaining arguments in the Python argument list are
889 optional. The C variables corresponding to optional arguments should
890 be initialized to their default value --- when an optional argument is
891 not specified, \cfunction{PyArg_ParseTuple()} does not touch the contents
892 of the corresponding C variable(s).
894 \item[\samp{:}]
895 The list of format units ends here; the string after the colon is used
896 as the function name in error messages (the ``associated value'' of
897 the exception that \cfunction{PyArg_ParseTuple()} raises).
899 \item[\samp{;}]
900 The list of format units ends here; the string after the colon is used
901 as the error message \emph{instead} of the default error message.
902 Clearly, \samp{:} and \samp{;} mutually exclude each other.
904 \end{description}
906 Some example calls:
908 \begin{verbatim}
909 int ok;
910 int i, j;
911 long k, l;
912 char *s;
913 int size;
915 ok = PyArg_ParseTuple(args, ""); /* No arguments */
916 /* Python call: f() */
917 \end{verbatim}
919 \begin{verbatim}
920 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
921 /* Possible Python call: f('whoops!') */
922 \end{verbatim}
924 \begin{verbatim}
925 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
926 /* Possible Python call: f(1, 2, 'three') */
927 \end{verbatim}
929 \begin{verbatim}
930 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
931 /* A pair of ints and a string, whose size is also returned */
932 /* Possible Python call: f((1, 2), 'three') */
933 \end{verbatim}
935 \begin{verbatim}
937 char *file;
938 char *mode = "r";
939 int bufsize = 0;
940 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
941 /* A string, and optionally another string and an integer */
942 /* Possible Python calls:
943 f('spam')
944 f('spam', 'w')
945 f('spam', 'wb', 100000) */
947 \end{verbatim}
949 \begin{verbatim}
951 int left, top, right, bottom, h, v;
952 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
953 &left, &top, &right, &bottom, &h, &v);
954 /* A rectangle and a point */
955 /* Possible Python call:
956 f(((0, 0), (400, 300)), (10, 10)) */
958 \end{verbatim}
960 \begin{verbatim}
962 Py_complex c;
963 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
964 /* a complex, also providing a function name for errors */
965 /* Possible Python call: myfunction(1+2j) */
967 \end{verbatim}
970 \section{Keyword Parsing with \cfunction{PyArg_ParseTupleAndKeywords()}
971 \label{parseTupleAndKeywords}}
973 The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
974 follows:
976 \begin{verbatim}
977 int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
978 char *format, char **kwlist, ...);
979 \end{verbatim}
981 The \var{arg} and \var{format} parameters are identical to those of the
982 \cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
983 is the dictionary of keywords received as the third parameter from the
984 Python runtime. The \var{kwlist} parameter is a \NULL{}-terminated
985 list of strings which identify the parameters; the names are matched
986 with the type information from \var{format} from left to right.
988 \strong{Note:} Nested tuples cannot be parsed when using keyword
989 arguments! Keyword parameters passed in which are not present in the
990 \var{kwlist} will cause \exception{TypeError} to be raised.
992 Here is an example module which uses keywords, based on an example by
993 Geoff Philbrick (\email{philbrick@hks.com}):%
994 \index{Philbrick, Geoff}
996 \begin{verbatim}
997 #include <stdio.h>
998 #include "Python.h"
1000 static PyObject *
1001 keywdarg_parrot(self, args, keywds)
1002 PyObject *self;
1003 PyObject *args;
1004 PyObject *keywds;
1006 int voltage;
1007 char *state = "a stiff";
1008 char *action = "voom";
1009 char *type = "Norwegian Blue";
1011 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
1013 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
1014 &voltage, &state, &action, &type))
1015 return NULL;
1017 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
1018 action, voltage);
1019 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
1021 Py_INCREF(Py_None);
1023 return Py_None;
1026 static PyMethodDef keywdarg_methods[] = {
1027 /* The cast of the function is necessary since PyCFunction values
1028 * only take two PyObject* parameters, and keywdarg_parrot() takes
1029 * three.
1031 {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS},
1032 {NULL, NULL} /* sentinel */
1035 void
1036 initkeywdarg()
1038 /* Create the module and add the functions */
1039 Py_InitModule("keywdarg", keywdarg_methods);
1041 \end{verbatim}
1044 \section{The \cfunction{Py_BuildValue()} Function
1045 \label{buildValue}}
1047 This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
1048 declared as follows:
1050 \begin{verbatim}
1051 PyObject *Py_BuildValue(char *format, ...);
1052 \end{verbatim}
1054 It recognizes a set of format units similar to the ones recognized by
1055 \cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
1056 function, not output) must not be pointers, just values. It returns a
1057 new Python object, suitable for returning from a C function called
1058 from Python.
1060 One difference with \cfunction{PyArg_ParseTuple()}: while the latter
1061 requires its first argument to be a tuple (since Python argument lists
1062 are always represented as tuples internally),
1063 \cfunction{Py_BuildValue()} does not always build a tuple. It builds
1064 a tuple only if its format string contains two or more format units.
1065 If the format string is empty, it returns \code{None}; if it contains
1066 exactly one format unit, it returns whatever object is described by
1067 that format unit. To force it to return a tuple of size 0 or one,
1068 parenthesize the format string.
1070 When memory buffers are passed as parameters to supply data to build
1071 objects, as for the \samp{s} and \samp{s\#} formats, the required data
1072 is copied. Buffers provided by the caller are never referenced by the
1073 objects created by \cfunction{Py_BuildValue()}. In other words, if
1074 your code invokes \cfunction{malloc()} and passes the allocated memory
1075 to \cfunction{Py_BuildValue()}, your code is responsible for
1076 calling \cfunction{free()} for that memory once
1077 \cfunction{Py_BuildValue()} returns.
1079 In the following description, the quoted form is the format unit; the
1080 entry in (round) parentheses is the Python object type that the format
1081 unit will return; and the entry in [square] brackets is the type of
1082 the C value(s) to be passed.
1084 The characters space, tab, colon and comma are ignored in format
1085 strings (but not within format units such as \samp{s\#}). This can be
1086 used to make long format strings a tad more readable.
1088 \begin{description}
1090 \item[\samp{s} (string) {[char *]}]
1091 Convert a null-terminated C string to a Python object. If the C
1092 string pointer is \NULL{}, \code{None} is used.
1094 \item[\samp{s\#} (string) {[char *, int]}]
1095 Convert a C string and its length to a Python object. If the C string
1096 pointer is \NULL{}, the length is ignored and \code{None} is
1097 returned.
1099 \item[\samp{z} (string or \code{None}) {[char *]}]
1100 Same as \samp{s}.
1102 \item[\samp{z\#} (string or \code{None}) {[char *, int]}]
1103 Same as \samp{s\#}.
1105 \item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1106 Convert a null-terminated buffer of Unicode (UCS-2) data to a Python
1107 Unicode object. If the Unicode buffer pointer is \NULL,
1108 \code{None} is returned.
1110 \item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1111 Convert a Unicode (UCS-2) data buffer and its length to a Python
1112 Unicode object. If the Unicode buffer pointer is \NULL, the length
1113 is ignored and \code{None} is returned.
1115 \item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1116 Convert a null-terminated buffer of Unicode (UCS-2) data to a Python Unicode
1117 object. If the Unicode buffer pointer is \NULL{}, \code{None} is returned.
1119 \item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1120 Convert a Unicode (UCS-2) data buffer and its length to a Python Unicode
1121 object. If the Unicode buffer pointer is \NULL{}, the length is ignored and
1122 \code{None} is returned.
1124 \item[\samp{i} (integer) {[int]}]
1125 Convert a plain C \ctype{int} to a Python integer object.
1127 \item[\samp{b} (integer) {[char]}]
1128 Same as \samp{i}.
1130 \item[\samp{h} (integer) {[short int]}]
1131 Same as \samp{i}.
1133 \item[\samp{l} (integer) {[long int]}]
1134 Convert a C \ctype{long int} to a Python integer object.
1136 \item[\samp{c} (string of length 1) {[char]}]
1137 Convert a C \ctype{int} representing a character to a Python string of
1138 length 1.
1140 \item[\samp{d} (float) {[double]}]
1141 Convert a C \ctype{double} to a Python floating point number.
1143 \item[\samp{f} (float) {[float]}]
1144 Same as \samp{d}.
1146 \item[\samp{O} (object) {[PyObject *]}]
1147 Pass a Python object untouched (except for its reference count, which
1148 is incremented by one). If the object passed in is a \NULL{}
1149 pointer, it is assumed that this was caused because the call producing
1150 the argument found an error and set an exception. Therefore,
1151 \cfunction{Py_BuildValue()} will return \NULL{} but won't raise an
1152 exception. If no exception has been raised yet,
1153 \cdata{PyExc_SystemError} is set.
1155 \item[\samp{S} (object) {[PyObject *]}]
1156 Same as \samp{O}.
1158 \item[\samp{U} (object) {[PyObject *]}]
1159 Same as \samp{O}.
1161 \item[\samp{N} (object) {[PyObject *]}]
1162 Same as \samp{O}, except it doesn't increment the reference count on
1163 the object. Useful when the object is created by a call to an object
1164 constructor in the argument list.
1166 \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
1167 Convert \var{anything} to a Python object through a \var{converter}
1168 function. The function is called with \var{anything} (which should be
1169 compatible with \ctype{void *}) as its argument and should return a
1170 ``new'' Python object, or \NULL{} if an error occurred.
1172 \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
1173 Convert a sequence of C values to a Python tuple with the same number
1174 of items.
1176 \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
1177 Convert a sequence of C values to a Python list with the same number
1178 of items.
1180 \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
1181 Convert a sequence of C values to a Python dictionary. Each pair of
1182 consecutive C values adds one item to the dictionary, serving as key
1183 and value, respectively.
1185 \end{description}
1187 If there is an error in the format string, the
1188 \cdata{PyExc_SystemError} exception is raised and \NULL{} returned.
1190 Examples (to the left the call, to the right the resulting Python value):
1192 \begin{verbatim}
1193 Py_BuildValue("") None
1194 Py_BuildValue("i", 123) 123
1195 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
1196 Py_BuildValue("s", "hello") 'hello'
1197 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
1198 Py_BuildValue("s#", "hello", 4) 'hell'
1199 Py_BuildValue("()") ()
1200 Py_BuildValue("(i)", 123) (123,)
1201 Py_BuildValue("(ii)", 123, 456) (123, 456)
1202 Py_BuildValue("(i,i)", 123, 456) (123, 456)
1203 Py_BuildValue("[i,i]", 123, 456) [123, 456]
1204 Py_BuildValue("{s:i,s:i}",
1205 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
1206 Py_BuildValue("((ii)(ii)) (ii)",
1207 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
1208 \end{verbatim}
1211 \section{Reference Counts
1212 \label{refcounts}}
1214 In languages like C or \Cpp{}, the programmer is responsible for
1215 dynamic allocation and deallocation of memory on the heap. In C,
1216 this is done using the functions \cfunction{malloc()} and
1217 \cfunction{free()}. In \Cpp{}, the operators \keyword{new} and
1218 \keyword{delete} are used with essentially the same meaning; they are
1219 actually implemented using \cfunction{malloc()} and
1220 \cfunction{free()}, so we'll restrict the following discussion to the
1221 latter.
1223 Every block of memory allocated with \cfunction{malloc()} should
1224 eventually be returned to the pool of available memory by exactly one
1225 call to \cfunction{free()}. It is important to call
1226 \cfunction{free()} at the right time. If a block's address is
1227 forgotten but \cfunction{free()} is not called for it, the memory it
1228 occupies cannot be reused until the program terminates. This is
1229 called a \dfn{memory leak}. On the other hand, if a program calls
1230 \cfunction{free()} for a block and then continues to use the block, it
1231 creates a conflict with re-use of the block through another
1232 \cfunction{malloc()} call. This is called \dfn{using freed memory}.
1233 It has the same bad consequences as referencing uninitialized data ---
1234 core dumps, wrong results, mysterious crashes.
1236 Common causes of memory leaks are unusual paths through the code. For
1237 instance, a function may allocate a block of memory, do some
1238 calculation, and then free the block again. Now a change in the
1239 requirements for the function may add a test to the calculation that
1240 detects an error condition and can return prematurely from the
1241 function. It's easy to forget to free the allocated memory block when
1242 taking this premature exit, especially when it is added later to the
1243 code. Such leaks, once introduced, often go undetected for a long
1244 time: the error exit is taken only in a small fraction of all calls,
1245 and most modern machines have plenty of virtual memory, so the leak
1246 only becomes apparent in a long-running process that uses the leaking
1247 function frequently. Therefore, it's important to prevent leaks from
1248 happening by having a coding convention or strategy that minimizes
1249 this kind of errors.
1251 Since Python makes heavy use of \cfunction{malloc()} and
1252 \cfunction{free()}, it needs a strategy to avoid memory leaks as well
1253 as the use of freed memory. The chosen method is called
1254 \dfn{reference counting}. The principle is simple: every object
1255 contains a counter, which is incremented when a reference to the
1256 object is stored somewhere, and which is decremented when a reference
1257 to it is deleted. When the counter reaches zero, the last reference
1258 to the object has been deleted and the object is freed.
1260 An alternative strategy is called \dfn{automatic garbage collection}.
1261 (Sometimes, reference counting is also referred to as a garbage
1262 collection strategy, hence my use of ``automatic'' to distinguish the
1263 two.) The big advantage of automatic garbage collection is that the
1264 user doesn't need to call \cfunction{free()} explicitly. (Another claimed
1265 advantage is an improvement in speed or memory usage --- this is no
1266 hard fact however.) The disadvantage is that for C, there is no
1267 truly portable automatic garbage collector, while reference counting
1268 can be implemented portably (as long as the functions \cfunction{malloc()}
1269 and \cfunction{free()} are available --- which the C Standard guarantees).
1270 Maybe some day a sufficiently portable automatic garbage collector
1271 will be available for C. Until then, we'll have to live with
1272 reference counts.
1274 \subsection{Reference Counting in Python
1275 \label{refcountsInPython}}
1277 There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
1278 which handle the incrementing and decrementing of the reference count.
1279 \cfunction{Py_DECREF()} also frees the object when the count reaches zero.
1280 For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
1281 makes a call through a function pointer in the object's \dfn{type
1282 object}. For this purpose (and others), every object also contains a
1283 pointer to its type object.
1285 The big question now remains: when to use \code{Py_INCREF(x)} and
1286 \code{Py_DECREF(x)}? Let's first introduce some terms. Nobody
1287 ``owns'' an object; however, you can \dfn{own a reference} to an
1288 object. An object's reference count is now defined as the number of
1289 owned references to it. The owner of a reference is responsible for
1290 calling \cfunction{Py_DECREF()} when the reference is no longer
1291 needed. Ownership of a reference can be transferred. There are three
1292 ways to dispose of an owned reference: pass it on, store it, or call
1293 \cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
1294 creates a memory leak.
1296 It is also possible to \dfn{borrow}\footnote{The metaphor of
1297 ``borrowing'' a reference is not completely correct: the owner still
1298 has a copy of the reference.} a reference to an object. The borrower
1299 of a reference should not call \cfunction{Py_DECREF()}. The borrower must
1300 not hold on to the object longer than the owner from which it was
1301 borrowed. Using a borrowed reference after the owner has disposed of
1302 it risks using freed memory and should be avoided
1303 completely.\footnote{Checking that the reference count is at least 1
1304 \strong{does not work} --- the reference count itself could be in
1305 freed memory and may thus be reused for another object!}
1307 The advantage of borrowing over owning a reference is that you don't
1308 need to take care of disposing of the reference on all possible paths
1309 through the code --- in other words, with a borrowed reference you
1310 don't run the risk of leaking when a premature exit is taken. The
1311 disadvantage of borrowing over leaking is that there are some subtle
1312 situations where in seemingly correct code a borrowed reference can be
1313 used after the owner from which it was borrowed has in fact disposed
1314 of it.
1316 A borrowed reference can be changed into an owned reference by calling
1317 \cfunction{Py_INCREF()}. This does not affect the status of the owner from
1318 which the reference was borrowed --- it creates a new owned reference,
1319 and gives full owner responsibilities (i.e., the new owner must
1320 dispose of the reference properly, as well as the previous owner).
1323 \subsection{Ownership Rules
1324 \label{ownershipRules}}
1326 Whenever an object reference is passed into or out of a function, it
1327 is part of the function's interface specification whether ownership is
1328 transferred with the reference or not.
1330 Most functions that return a reference to an object pass on ownership
1331 with the reference. In particular, all functions whose function it is
1332 to create a new object, e.g.\ \cfunction{PyInt_FromLong()} and
1333 \cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if in
1334 fact, in some cases, you don't receive a reference to a brand new
1335 object, you still receive ownership of the reference. For instance,
1336 \cfunction{PyInt_FromLong()} maintains a cache of popular values and can
1337 return a reference to a cached item.
1339 Many functions that extract objects from other objects also transfer
1340 ownership with the reference, for instance
1341 \cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
1342 however, since a few common routines are exceptions:
1343 \cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
1344 \cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
1345 all return references that you borrow from the tuple, list or
1346 dictionary.
1348 The function \cfunction{PyImport_AddModule()} also returns a borrowed
1349 reference, even though it may actually create the object it returns:
1350 this is possible because an owned reference to the object is stored in
1351 \code{sys.modules}.
1353 When you pass an object reference into another function, in general,
1354 the function borrows the reference from you --- if it needs to store
1355 it, it will use \cfunction{Py_INCREF()} to become an independent
1356 owner. There are exactly two important exceptions to this rule:
1357 \cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
1358 functions take over ownership of the item passed to them --- even if
1359 they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
1360 take over ownership --- they are ``normal.'')
1362 When a C function is called from Python, it borrows references to its
1363 arguments from the caller. The caller owns a reference to the object,
1364 so the borrowed reference's lifetime is guaranteed until the function
1365 returns. Only when such a borrowed reference must be stored or passed
1366 on, it must be turned into an owned reference by calling
1367 \cfunction{Py_INCREF()}.
1369 The object reference returned from a C function that is called from
1370 Python must be an owned reference --- ownership is tranferred from the
1371 function to its caller.
1374 \subsection{Thin Ice
1375 \label{thinIce}}
1377 There are a few situations where seemingly harmless use of a borrowed
1378 reference can lead to problems. These all have to do with implicit
1379 invocations of the interpreter, which can cause the owner of a
1380 reference to dispose of it.
1382 The first and most important case to know about is using
1383 \cfunction{Py_DECREF()} on an unrelated object while borrowing a
1384 reference to a list item. For instance:
1386 \begin{verbatim}
1387 bug(PyObject *list) {
1388 PyObject *item = PyList_GetItem(list, 0);
1390 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1391 PyObject_Print(item, stdout, 0); /* BUG! */
1393 \end{verbatim}
1395 This function first borrows a reference to \code{list[0]}, then
1396 replaces \code{list[1]} with the value \code{0}, and finally prints
1397 the borrowed reference. Looks harmless, right? But it's not!
1399 Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
1400 owns references to all its items, so when item 1 is replaced, it has
1401 to dispose of the original item 1. Now let's suppose the original
1402 item 1 was an instance of a user-defined class, and let's further
1403 suppose that the class defined a \method{__del__()} method. If this
1404 class instance has a reference count of 1, disposing of it will call
1405 its \method{__del__()} method.
1407 Since it is written in Python, the \method{__del__()} method can execute
1408 arbitrary Python code. Could it perhaps do something to invalidate
1409 the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
1410 that the list passed into \cfunction{bug()} is accessible to the
1411 \method{__del__()} method, it could execute a statement to the effect of
1412 \samp{del list[0]}, and assuming this was the last reference to that
1413 object, it would free the memory associated with it, thereby
1414 invalidating \code{item}.
1416 The solution, once you know the source of the problem, is easy:
1417 temporarily increment the reference count. The correct version of the
1418 function reads:
1420 \begin{verbatim}
1421 no_bug(PyObject *list) {
1422 PyObject *item = PyList_GetItem(list, 0);
1424 Py_INCREF(item);
1425 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1426 PyObject_Print(item, stdout, 0);
1427 Py_DECREF(item);
1429 \end{verbatim}
1431 This is a true story. An older version of Python contained variants
1432 of this bug and someone spent a considerable amount of time in a C
1433 debugger to figure out why his \method{__del__()} methods would fail...
1435 The second case of problems with a borrowed reference is a variant
1436 involving threads. Normally, multiple threads in the Python
1437 interpreter can't get in each other's way, because there is a global
1438 lock protecting Python's entire object space. However, it is possible
1439 to temporarily release this lock using the macro
1440 \code{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using
1441 \code{Py_END_ALLOW_THREADS}. This is common around blocking I/O
1442 calls, to let other threads use the CPU while waiting for the I/O to
1443 complete. Obviously, the following function has the same problem as
1444 the previous one:
1446 \begin{verbatim}
1447 bug(PyObject *list) {
1448 PyObject *item = PyList_GetItem(list, 0);
1449 Py_BEGIN_ALLOW_THREADS
1450 ...some blocking I/O call...
1451 Py_END_ALLOW_THREADS
1452 PyObject_Print(item, stdout, 0); /* BUG! */
1454 \end{verbatim}
1457 \subsection{NULL Pointers
1458 \label{nullPointers}}
1460 In general, functions that take object references as arguments do not
1461 expect you to pass them \NULL{} pointers, and will dump core (or
1462 cause later core dumps) if you do so. Functions that return object
1463 references generally return \NULL{} only to indicate that an
1464 exception occurred. The reason for not testing for \NULL{}
1465 arguments is that functions often pass the objects they receive on to
1466 other function --- if each function were to test for \NULL{},
1467 there would be a lot of redundant tests and the code would run more
1468 slowly.
1470 It is better to test for \NULL{} only at the ``source'', i.e.\ when a
1471 pointer that may be \NULL{} is received, e.g.\ from
1472 \cfunction{malloc()} or from a function that may raise an exception.
1474 The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
1475 do not check for \NULL{} pointers --- however, their variants
1476 \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
1478 The macros for checking for a particular object type
1479 (\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
1480 again, there is much code that calls several of these in a row to test
1481 an object against various different expected types, and this would
1482 generate redundant tests. There are no variants with \NULL{}
1483 checking.
1485 The C function calling mechanism guarantees that the argument list
1486 passed to C functions (\code{args} in the examples) is never
1487 \NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
1488 These guarantees don't hold when you use the ``old'' style
1489 calling convention --- this is still found in much existing code.}
1491 It is a severe error to ever let a \NULL{} pointer ``escape'' to
1492 the Python user.
1494 % Frank Stajano:
1495 % A pedagogically buggy example, along the lines of the previous listing,
1496 % would be helpful here -- showing in more concrete terms what sort of
1497 % actions could cause the problem. I can't very well imagine it from the
1498 % description.
1501 \section{Writing Extensions in \Cpp{}
1502 \label{cplusplus}}
1504 It is possible to write extension modules in \Cpp{}. Some restrictions
1505 apply. If the main program (the Python interpreter) is compiled and
1506 linked by the C compiler, global or static objects with constructors
1507 cannot be used. This is not a problem if the main program is linked
1508 by the \Cpp{} compiler. Functions that will be called by the
1509 Python interpreter (in particular, module initalization functions)
1510 have to be declared using \code{extern "C"}.
1511 It is unnecessary to enclose the Python header files in
1512 \code{extern "C" \{...\}} --- they use this form already if the symbol
1513 \samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
1514 symbol).
1517 \section{Providing a C API for an Extension Module
1518 \label{using-cobjects}}
1519 \sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
1521 Many extension modules just provide new functions and types to be
1522 used from Python, but sometimes the code in an extension module can
1523 be useful for other extension modules. For example, an extension
1524 module could implement a type ``collection'' which works like lists
1525 without order. Just like the standard Python list type has a C API
1526 which permits extension modules to create and manipulate lists, this
1527 new collection type should have a set of C functions for direct
1528 manipulation from other extension modules.
1530 At first sight this seems easy: just write the functions (without
1531 declaring them \keyword{static}, of course), provide an appropriate
1532 header file, and document the C API. And in fact this would work if
1533 all extension modules were always linked statically with the Python
1534 interpreter. When modules are used as shared libraries, however, the
1535 symbols defined in one module may not be visible to another module.
1536 The details of visibility depend on the operating system; some systems
1537 use one global namespace for the Python interpreter and all extension
1538 modules (e.g.\ Windows), whereas others require an explicit list of
1539 imported symbols at module link time (e.g.\ AIX), or offer a choice of
1540 different strategies (most Unices). And even if symbols are globally
1541 visible, the module whose functions one wishes to call might not have
1542 been loaded yet!
1544 Portability therefore requires not to make any assumptions about
1545 symbol visibility. This means that all symbols in extension modules
1546 should be declared \keyword{static}, except for the module's
1547 initialization function, in order to avoid name clashes with other
1548 extension modules (as discussed in section~\ref{methodTable}). And it
1549 means that symbols that \emph{should} be accessible from other
1550 extension modules must be exported in a different way.
1552 Python provides a special mechanism to pass C-level information (i.e.
1553 pointers) from one extension module to another one: CObjects.
1554 A CObject is a Python data type which stores a pointer (\ctype{void
1555 *}). CObjects can only be created and accessed via their C API, but
1556 they can be passed around like any other Python object. In particular,
1557 they can be assigned to a name in an extension module's namespace.
1558 Other extension modules can then import this module, retrieve the
1559 value of this name, and then retrieve the pointer from the CObject.
1561 There are many ways in which CObjects can be used to export the C API
1562 of an extension module. Each name could get its own CObject, or all C
1563 API pointers could be stored in an array whose address is published in
1564 a CObject. And the various tasks of storing and retrieving the pointers
1565 can be distributed in different ways between the module providing the
1566 code and the client modules.
1568 The following example demonstrates an approach that puts most of the
1569 burden on the writer of the exporting module, which is appropriate
1570 for commonly used library modules. It stores all C API pointers
1571 (just one in the example!) in an array of \ctype{void} pointers which
1572 becomes the value of a CObject. The header file corresponding to
1573 the module provides a macro that takes care of importing the module
1574 and retrieving its C API pointers; client modules only have to call
1575 this macro before accessing the C API.
1577 The exporting module is a modification of the \module{spam} module from
1578 section~\ref{simpleExample}. The function \function{spam.system()}
1579 does not call the C library function \cfunction{system()} directly,
1580 but a function \cfunction{PySpam_System()}, which would of course do
1581 something more complicated in reality (such as adding ``spam'' to
1582 every command). This function \cfunction{PySpam_System()} is also
1583 exported to other extension modules.
1585 The function \cfunction{PySpam_System()} is a plain C function,
1586 declared \keyword{static} like everything else:
1588 \begin{verbatim}
1589 static int
1590 PySpam_System(command)
1591 char *command;
1593 return system(command);
1595 \end{verbatim}
1597 The function \cfunction{spam_system()} is modified in a trivial way:
1599 \begin{verbatim}
1600 static PyObject *
1601 spam_system(self, args)
1602 PyObject *self;
1603 PyObject *args;
1605 char *command;
1606 int sts;
1608 if (!PyArg_ParseTuple(args, "s", &command))
1609 return NULL;
1610 sts = PySpam_System(command);
1611 return Py_BuildValue("i", sts);
1613 \end{verbatim}
1615 In the beginning of the module, right after the line
1617 \begin{verbatim}
1618 #include "Python.h"
1619 \end{verbatim}
1621 two more lines must be added:
1623 \begin{verbatim}
1624 #define SPAM_MODULE
1625 #include "spammodule.h"
1626 \end{verbatim}
1628 The \code{\#define} is used to tell the header file that it is being
1629 included in the exporting module, not a client module. Finally,
1630 the module's initialization function must take care of initializing
1631 the C API pointer array:
1633 \begin{verbatim}
1634 void
1635 initspam()
1637 PyObject *m, *d;
1638 static void *PySpam_API[PySpam_API_pointers];
1639 PyObject *c_api_object;
1640 m = Py_InitModule("spam", SpamMethods);
1642 /* Initialize the C API pointer array */
1643 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1645 /* Create a CObject containing the API pointer array's address */
1646 c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
1648 /* Create a name for this object in the module's namespace */
1649 d = PyModule_GetDict(m);
1650 PyDict_SetItemString(d, "_C_API", c_api_object);
1652 \end{verbatim}
1654 Note that \code{PySpam_API} is declared \code{static}; otherwise
1655 the pointer array would disappear when \code{initspam} terminates!
1657 The bulk of the work is in the header file \file{spammodule.h},
1658 which looks like this:
1660 \begin{verbatim}
1661 #ifndef Py_SPAMMODULE_H
1662 #define Py_SPAMMODULE_H
1663 #ifdef __cplusplus
1664 extern "C" {
1665 #endif
1667 /* Header file for spammodule */
1669 /* C API functions */
1670 #define PySpam_System_NUM 0
1671 #define PySpam_System_RETURN int
1672 #define PySpam_System_PROTO (char *command)
1674 /* Total number of C API pointers */
1675 #define PySpam_API_pointers 1
1678 #ifdef SPAM_MODULE
1679 /* This section is used when compiling spammodule.c */
1681 static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1683 #else
1684 /* This section is used in modules that use spammodule's API */
1686 static void **PySpam_API;
1688 #define PySpam_System \
1689 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1691 #define import_spam() \
1693 PyObject *module = PyImport_ImportModule("spam"); \
1694 if (module != NULL) { \
1695 PyObject *module_dict = PyModule_GetDict(module); \
1696 PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \
1697 if (PyCObject_Check(c_api_object)) { \
1698 PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \
1703 #endif
1705 #ifdef __cplusplus
1707 #endif
1709 #endif /* !defined(Py_SPAMMODULE_H */
1710 \end{verbatim}
1712 All that a client module must do in order to have access to the
1713 function \cfunction{PySpam_System()} is to call the function (or
1714 rather macro) \cfunction{import_spam()} in its initialization
1715 function:
1717 \begin{verbatim}
1718 void
1719 initclient()
1721 PyObject *m;
1723 Py_InitModule("client", ClientMethods);
1724 import_spam();
1726 \end{verbatim}
1728 The main disadvantage of this approach is that the file
1729 \file{spammodule.h} is rather complicated. However, the
1730 basic structure is the same for each function that is
1731 exported, so it has to be learned only once.
1733 Finally it should be mentioned that CObjects offer additional
1734 functionality, which is especially useful for memory allocation and
1735 deallocation of the pointer stored in a CObject. The details
1736 are described in the \citetitle[../api/api.html]{Python/C API
1737 Reference Manual} in the section ``CObjects'' and in the
1738 implementation of CObjects (files \file{Include/cobject.h} and
1739 \file{Objects/cobject.c} in the Python source code distribution).
1742 \chapter{Building C and \Cpp{} Extensions on \UNIX{}
1743 \label{building-on-unix}}
1745 \sectionauthor{Jim Fulton}{jim@Digicool.com}
1748 %The make file make file, building C extensions on Unix
1751 Starting in Python 1.4, Python provides a special make file for
1752 building make files for building dynamically-linked extensions and
1753 custom interpreters. The make file make file builds a make file
1754 that reflects various system variables determined by configure when
1755 the Python interpreter was built, so people building module's don't
1756 have to resupply these settings. This vastly simplifies the process
1757 of building extensions and custom interpreters on Unix systems.
1759 The make file make file is distributed as the file
1760 \file{Misc/Makefile.pre.in} in the Python source distribution. The
1761 first step in building extensions or custom interpreters is to copy
1762 this make file to a development directory containing extension module
1763 source.
1765 The make file make file, \file{Makefile.pre.in} uses metadata
1766 provided in a file named \file{Setup}. The format of the \file{Setup}
1767 file is the same as the \file{Setup} (or \file{Setup.in}) file
1768 provided in the \file{Modules/} directory of the Python source
1769 distribution. The \file{Setup} file contains variable definitions:
1771 \begin{verbatim}
1772 EC=/projects/ExtensionClass
1773 \end{verbatim}
1775 and module description lines. It can also contain blank lines and
1776 comment lines that start with \character{\#}.
1778 A module description line includes a module name, source files,
1779 options, variable references, and other input files, such
1780 as libraries or object files. Consider a simple example:
1782 \begin{verbatim}
1783 ExtensionClass ExtensionClass.c
1784 \end{verbatim}
1786 This is the simplest form of a module definition line. It defines a
1787 module, \module{ExtensionClass}, which has a single source file,
1788 \file{ExtensionClass.c}.
1790 This slightly more complex example uses an \strong{-I} option to
1791 specify an include directory:
1793 \begin{verbatim}
1794 EC=/projects/ExtensionClass
1795 cPersistence cPersistence.c -I$(EC)
1796 \end{verbatim} % $ <-- bow to font lock
1798 This example also illustrates the format for variable references.
1800 For systems that support dynamic linking, the \file{Setup} file should
1801 begin:
1803 \begin{verbatim}
1804 *shared*
1805 \end{verbatim}
1807 to indicate that the modules defined in \file{Setup} are to be built
1808 as dynamically linked modules. A line containing only \samp{*static*}
1809 can be used to indicate the subsequently listed modules should be
1810 statically linked.
1812 Here is a complete \file{Setup} file for building a
1813 \module{cPersistent} module:
1815 \begin{verbatim}
1816 # Set-up file to build the cPersistence module.
1817 # Note that the text should begin in the first column.
1818 *shared*
1820 # We need the path to the directory containing the ExtensionClass
1821 # include file.
1822 EC=/projects/ExtensionClass
1823 cPersistence cPersistence.c -I$(EC)
1824 \end{verbatim} % $ <-- bow to font lock
1826 After the \file{Setup} file has been created, \file{Makefile.pre.in}
1827 is run with the \samp{boot} target to create a make file:
1829 \begin{verbatim}
1830 make -f Makefile.pre.in boot
1831 \end{verbatim}
1833 This creates the file, Makefile. To build the extensions, simply
1834 run the created make file:
1836 \begin{verbatim}
1837 make
1838 \end{verbatim}
1840 It's not necessary to re-run \file{Makefile.pre.in} if the
1841 \file{Setup} file is changed. The make file automatically rebuilds
1842 itself if the \file{Setup} file changes.
1845 \section{Building Custom Interpreters \label{custom-interps}}
1847 The make file built by \file{Makefile.pre.in} can be run with the
1848 \samp{static} target to build an interpreter:
1850 \begin{verbatim}
1851 make static
1852 \end{verbatim}
1854 Any modules defined in the Setup file before the \samp{*shared*} line
1855 will be statically linked into the interpreter. Typically, a
1856 \samp{*shared*} line is omitted from the Setup file when a custom
1857 interpreter is desired.
1860 \section{Module Definition Options \label{module-defn-options}}
1862 Several compiler options are supported:
1864 \begin{tableii}{l|l}{}{Option}{Meaning}
1865 \lineii{-C}{Tell the C pre-processor not to discard comments}
1866 \lineii{-D\var{name}=\var{value}}{Define a macro}
1867 \lineii{-I\var{dir}}{Specify an include directory, \var{dir}}
1868 \lineii{-L\var{dir}}{Specify a link-time library directory, \var{dir}}
1869 \lineii{-R\var{dir}}{Specify a run-time library directory, \var{dir}}
1870 \lineii{-l\var{lib}}{Link a library, \var{lib}}
1871 \lineii{-U\var{name}}{Undefine a macro}
1872 \end{tableii}
1874 Other compiler options can be included (snuck in) by putting them
1875 in variables.
1877 Source files can include files with \file{.c}, \file{.C}, \file{.cc},
1878 \file{.cpp}, \file{.cxx}, and \file{.c++} extensions.
1880 Other input files include files with \file{.a}, \file{.o}, \file{.sl},
1881 and \file{.so} extensions.
1884 \section{Example \label{module-defn-example}}
1886 Here is a more complicated example from \file{Modules/Setup.in}:
1888 \begin{verbatim}
1889 GMP=/ufs/guido/src/gmp
1890 mpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a
1891 \end{verbatim}
1893 which could also be written as:
1895 \begin{verbatim}
1896 mpz mpzmodule.c -I$(GMP) -L$(GMP) -lgmp
1897 \end{verbatim}
1900 \section{Distributing your extension modules
1901 \label{distributing}}
1903 When distributing your extension modules in source form, make sure to
1904 include a \file{Setup} file. The \file{Setup} file should be named
1905 \file{Setup.in} in the distribution. The make file make file,
1906 \file{Makefile.pre.in}, will copy \file{Setup.in} to \file{Setup}.
1907 Distributing a \file{Setup.in} file makes it easy for people to
1908 customize the \file{Setup} file while keeping the original in
1909 \file{Setup.in}.
1911 It is a good idea to include a copy of \file{Makefile.pre.in} for
1912 people who do not have a source distribution of Python.
1914 Do not distribute a make file. People building your modules
1915 should use \file{Makefile.pre.in} to build their own make file. A
1916 \file{README} file included in the package should provide simple
1917 instructions to perform the build.
1919 Work is being done to make building and installing Python extensions
1920 easier for all platforms; this work in likely to supplant the current
1921 approach at some point in the future. For more information or to
1922 participate in the effort, refer to
1923 \url{http://www.python.org/sigs/distutils-sig/} on the Python Web
1924 site.
1927 \chapter{Building C and \Cpp{} Extensions on Windows
1928 \label{building-on-windows}}
1931 This chapter briefly explains how to create a Windows extension module
1932 for Python using Microsoft Visual \Cpp{}, and follows with more
1933 detailed background information on how it works. The explanatory
1934 material is useful for both the Windows programmer learning to build
1935 Python extensions and the \UNIX{} programmer interested in producing
1936 software which can be successfully built on both \UNIX{} and Windows.
1939 \section{A Cookbook Approach \label{win-cookbook}}
1941 \sectionauthor{Neil Schemenauer}{neil_schemenauer@transcanada.com}
1943 This section provides a recipe for building a Python extension on
1944 Windows.
1946 Grab the binary installer from \url{http://www.python.org/} and
1947 install Python. The binary installer has all of the required header
1948 files except for \file{config.h}.
1950 Get the source distribution and extract it into a convenient location.
1951 Copy the \file{config.h} from the \file{PC/} directory into the
1952 \file{include/} directory created by the installer.
1954 Create a \file{Setup} file for your extension module, as described in
1955 chapter \ref{building-on-unix}.
1957 Get David Ascher's \file{compile.py} script from
1958 \url{http://starship.python.net/crew/da/compile/}. Run the script to
1959 create Microsoft Visual \Cpp{} project files.
1961 Open the DSW file in Visual \Cpp{} and select \strong{Build}.
1963 If your module creates a new type, you may have trouble with this line:
1965 \begin{verbatim}
1966 PyObject_HEAD_INIT(&PyType_Type)
1967 \end{verbatim}
1969 Change it to:
1971 \begin{verbatim}
1972 PyObject_HEAD_INIT(NULL)
1973 \end{verbatim}
1975 and add the following to the module initialization function:
1977 \begin{verbatim}
1978 MyObject_Type.ob_type = &PyType_Type;
1979 \end{verbatim}
1981 Refer to section 3 of the Python FAQ
1982 (\url{http://www.python.org/doc/FAQ.html}) for details on why you must
1983 do this.
1986 \section{Differences Between \UNIX{} and Windows
1987 \label{dynamic-linking}}
1988 \sectionauthor{Chris Phoenix}{cphoenix@best.com}
1991 \UNIX{} and Windows use completely different paradigms for run-time
1992 loading of code. Before you try to build a module that can be
1993 dynamically loaded, be aware of how your system works.
1995 In \UNIX{}, a shared object (\file{.so}) file contains code to be used by the
1996 program, and also the names of functions and data that it expects to
1997 find in the program. When the file is joined to the program, all
1998 references to those functions and data in the file's code are changed
1999 to point to the actual locations in the program where the functions
2000 and data are placed in memory. This is basically a link operation.
2002 In Windows, a dynamic-link library (\file{.dll}) file has no dangling
2003 references. Instead, an access to functions or data goes through a
2004 lookup table. So the DLL code does not have to be fixed up at runtime
2005 to refer to the program's memory; instead, the code already uses the
2006 DLL's lookup table, and the lookup table is modified at runtime to
2007 point to the functions and data.
2009 In \UNIX{}, there is only one type of library file (\file{.a}) which
2010 contains code from several object files (\file{.o}). During the link
2011 step to create a shared object file (\file{.so}), the linker may find
2012 that it doesn't know where an identifier is defined. The linker will
2013 look for it in the object files in the libraries; if it finds it, it
2014 will include all the code from that object file.
2016 In Windows, there are two types of library, a static library and an
2017 import library (both called \file{.lib}). A static library is like a
2018 \UNIX{} \file{.a} file; it contains code to be included as necessary.
2019 An import library is basically used only to reassure the linker that a
2020 certain identifier is legal, and will be present in the program when
2021 the DLL is loaded. So the linker uses the information from the
2022 import library to build the lookup table for using identifiers that
2023 are not included in the DLL. When an application or a DLL is linked,
2024 an import library may be generated, which will need to be used for all
2025 future DLLs that depend on the symbols in the application or DLL.
2027 Suppose you are building two dynamic-load modules, B and C, which should
2028 share another block of code A. On \UNIX{}, you would \emph{not} pass
2029 \file{A.a} to the linker for \file{B.so} and \file{C.so}; that would
2030 cause it to be included twice, so that B and C would each have their
2031 own copy. In Windows, building \file{A.dll} will also build
2032 \file{A.lib}. You \emph{do} pass \file{A.lib} to the linker for B and
2033 C. \file{A.lib} does not contain code; it just contains information
2034 which will be used at runtime to access A's code.
2036 In Windows, using an import library is sort of like using \samp{import
2037 spam}; it gives you access to spam's names, but does not create a
2038 separate copy. On \UNIX{}, linking with a library is more like
2039 \samp{from spam import *}; it does create a separate copy.
2042 \section{Using DLLs in Practice \label{win-dlls}}
2043 \sectionauthor{Chris Phoenix}{cphoenix@best.com}
2045 Windows Python is built in Microsoft Visual \Cpp{}; using other
2046 compilers may or may not work (though Borland seems to). The rest of
2047 this section is MSV\Cpp{} specific.
2049 When creating DLLs in Windows, you must pass \file{python15.lib} to
2050 the linker. To build two DLLs, spam and ni (which uses C functions
2051 found in spam), you could use these commands:
2053 \begin{verbatim}
2054 cl /LD /I/python/include spam.c ../libs/python15.lib
2055 cl /LD /I/python/include ni.c spam.lib ../libs/python15.lib
2056 \end{verbatim}
2058 The first command created three files: \file{spam.obj},
2059 \file{spam.dll} and \file{spam.lib}. \file{Spam.dll} does not contain
2060 any Python functions (such as \cfunction{PyArg_ParseTuple()}), but it
2061 does know how to find the Python code thanks to \file{python15.lib}.
2063 The second command created \file{ni.dll} (and \file{.obj} and
2064 \file{.lib}), which knows how to find the necessary functions from
2065 spam, and also from the Python executable.
2067 Not every identifier is exported to the lookup table. If you want any
2068 other modules (including Python) to be able to see your identifiers,
2069 you have to say \samp{_declspec(dllexport)}, as in \samp{void
2070 _declspec(dllexport) initspam(void)} or \samp{PyObject
2071 _declspec(dllexport) *NiGetSpamData(void)}.
2073 Developer Studio will throw in a lot of import libraries that you do
2074 not really need, adding about 100K to your executable. To get rid of
2075 them, use the Project Settings dialog, Link tab, to specify
2076 \emph{ignore default libraries}. Add the correct
2077 \file{msvcrt\var{xx}.lib} to the list of libraries.
2080 \chapter{Embedding Python in Another Application
2081 \label{embedding}}
2083 Embedding Python is similar to extending it, but not quite. The
2084 difference is that when you extend Python, the main program of the
2085 application is still the Python interpreter, while if you embed
2086 Python, the main program may have nothing to do with Python ---
2087 instead, some parts of the application occasionally call the Python
2088 interpreter to run some Python code.
2090 So if you are embedding Python, you are providing your own main
2091 program. One of the things this main program has to do is initialize
2092 the Python interpreter. At the very least, you have to call the
2093 function \cfunction{Py_Initialize()} (on MacOS, call
2094 \cfunction{PyMac_Initialize()} instead). There are optional calls to
2095 pass command line arguments to Python. Then later you can call the
2096 interpreter from any part of the application.
2098 There are several different ways to call the interpreter: you can pass
2099 a string containing Python statements to
2100 \cfunction{PyRun_SimpleString()}, or you can pass a stdio file pointer
2101 and a file name (for identification in error messages only) to
2102 \cfunction{PyRun_SimpleFile()}. You can also call the lower-level
2103 operations described in the previous chapters to construct and use
2104 Python objects.
2106 A simple demo of embedding Python can be found in the directory
2107 \file{Demo/embed/} of the source distribution.
2110 \section{Embedding Python in \Cpp{}
2111 \label{embeddingInCplusplus}}
2113 It is also possible to embed Python in a \Cpp{} program; precisely how this
2114 is done will depend on the details of the \Cpp{} system used; in general you
2115 will need to write the main program in \Cpp{}, and use the \Cpp{} compiler
2116 to compile and link your program. There is no need to recompile Python
2117 itself using \Cpp{}.
2120 \section{Linking Requirements
2121 \label{link-reqs}}
2123 While the \program{configure} script shipped with the Python sources
2124 will correctly build Python to export the symbols needed by
2125 dynamically linked extensions, this is not automatically inherited by
2126 applications which embed the Python library statically, at least on
2127 \UNIX. This is an issue when the application is linked to the static
2128 runtime library (\file{libpython.a}) and needs to load dynamic
2129 extensions (implemented as \file{.so} files).
2131 The problem is that some entry points are defined by the Python
2132 runtime solely for extension modules to use. If the embedding
2133 application does not use any of these entry points, some linkers will
2134 not include those entries in the symbol table of the finished
2135 executable. Some additional options are needed to inform the linker
2136 not to remove these symbols.
2138 Determining the right options to use for any given platform can be
2139 quite difficult, but fortunately the Python configuration already has
2140 those values. To retrieve them from an installed Python interpreter,
2141 start an interactive interpreter and have a short session like this:
2143 \begin{verbatim}
2144 >>> import distutils.sysconfig
2145 >>> distutils.sysconfig.LINKFORSHARED
2146 '-Xlinker -export-dynamic'
2147 \end{verbatim}
2148 \refstmodindex{distutils.sysconfig}
2150 The contents of the string presented will be the options that should
2151 be used. If the string is empty, there's no need to add any
2152 additional options. The \constant{LINKFORSHARED} definition
2153 corresponds to the variable of the same name in Python's top-level
2154 \file{Makefile}.
2157 \appendix
2158 \chapter{Reporting Bugs}
2159 \input{reportingbugs}
2161 \end{document}