blob: c29062c898781a5f6558b24e4ab5453dacf15940 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002
Guido van Rossumd358afe1998-12-23 05:02:08 +00003% XXX PM explain how to add new types to Python
Guido van Rossum5049bcb1995-03-13 16:55:23 +00004
Guido van Rossum6938f061994-08-01 12:22:53 +00005\title{Extending and Embedding the Python Interpreter}
Guido van Rossum7a2dba21993-11-05 14:45:11 +00006
Guido van Rossum16cd7f91994-10-06 10:29:26 +00007\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +00008
Guido van Rossum7a2dba21993-11-05 14:45:11 +00009% Tell \index to actually write the .idx file
10\makeindex
11
12\begin{document}
13
Guido van Rossum7a2dba21993-11-05 14:45:11 +000014\maketitle
15
Fred Drake9f86b661998-07-28 21:55:19 +000016\ifhtml
17\chapter*{Front Matter\label{front}}
18\fi
19
Guido van Rossum16cd7f91994-10-06 10:29:26 +000020\input{copyright}
21
Fred Drake33698f81999-02-16 23:06:32 +000022%begin{latexonly}
23\vspace{1in}
24%end{latexonly}
25\strong{\large Acknowledgements}
26
27% XXX This needs to be checked and updated manually before each
28% release.
29
30The following people have contributed sections to this document: Jim
31Fulton, Konrad Hinsen, Chris Phoenix, and Neil Schemenauer.
32
Guido van Rossum7a2dba21993-11-05 14:45:11 +000033\begin{abstract}
34
35\noindent
Guido van Rossumb92112d1995-03-20 14:24:09 +000036Python is an interpreted, object-oriented programming language. This
Fred Drakeec9fbe91999-02-15 16:20:25 +000037document describes how to write modules in C or \Cpp{} to extend the
Guido van Rossumb92112d1995-03-20 14:24:09 +000038Python interpreter with new modules. Those modules can define new
39functions but also new object types and their methods. The document
40also describes how to embed the Python interpreter in another
41application, for use as an extension language. Finally, it shows how
42to compile and link extension modules so that they can be loaded
43dynamically (at run time) into the interpreter, if the underlying
44operating system supports this feature.
45
46This document assumes basic knowledge about Python. For an informal
Fred Drake9fa76f11999-11-10 16:01:43 +000047introduction to the language, see the
48\citetitle[../tut/tut.html]{Python Tutorial}. The
49\citetitle[../ref/ref.html]{Python Reference Manual} gives a more
50formal definition of the language. The
51\citetitle[../lib/lib.html]{Python Library Reference} documents the
52existing object types, functions and modules (both built-in and
53written in Python) that give the language its wide application range.
Guido van Rossum7a2dba21993-11-05 14:45:11 +000054
Fred Drakeec9fbe91999-02-15 16:20:25 +000055For a detailed description of the whole Python/C API, see the separate
Fred Drake9fa76f11999-11-10 16:01:43 +000056\citetitle[../api/api.html]{Python/C API Reference Manual}.
Guido van Rossumfdacc581997-10-07 14:40:16 +000057
Guido van Rossum7a2dba21993-11-05 14:45:11 +000058\end{abstract}
59
Fred Drake4d4f9e71998-01-13 22:25:02 +000060\tableofcontents
Guido van Rossum7a2dba21993-11-05 14:45:11 +000061
Guido van Rossumdb65a6c1993-11-05 17:11:16 +000062
Fred Drake8e015171999-02-17 18:12:14 +000063\chapter{Extending Python with C or \Cpp{} \label{intro}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +000064
Guido van Rossum6f0132f1993-11-19 13:13:22 +000065
Guido van Rossumb92112d1995-03-20 14:24:09 +000066It is quite easy to add new built-in modules to Python, if you know
Fred Drakeec9fbe91999-02-15 16:20:25 +000067how to program in C. Such \dfn{extension modules} can do two things
Guido van Rossumb92112d1995-03-20 14:24:09 +000068that can't be done directly in Python: they can implement new built-in
Fred Drakeec9fbe91999-02-15 16:20:25 +000069object types, and they can call C library functions and system calls.
Guido van Rossum6938f061994-08-01 12:22:53 +000070
Guido van Rossum5049bcb1995-03-13 16:55:23 +000071To support extensions, the Python API (Application Programmers
Guido van Rossumb92112d1995-03-20 14:24:09 +000072Interface) defines a set of functions, macros and variables that
73provide access to most aspects of the Python run-time system. The
Fred Drakeec9fbe91999-02-15 16:20:25 +000074Python API is incorporated in a C source file by including the header
Guido van Rossumb92112d1995-03-20 14:24:09 +000075\code{"Python.h"}.
Guido van Rossum6938f061994-08-01 12:22:53 +000076
Guido van Rossumb92112d1995-03-20 14:24:09 +000077The compilation of an extension module depends on its intended use as
Fred Drake54fd8452000-04-03 04:54:28 +000078well as on your system setup; details are given in later chapters.
Guido van Rossum6938f061994-08-01 12:22:53 +000079
Guido van Rossum7a2dba21993-11-05 14:45:11 +000080
Fred Drake5e8aa541998-11-16 18:34:07 +000081\section{A Simple Example
82 \label{simpleExample}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +000083
Guido van Rossumb92112d1995-03-20 14:24:09 +000084Let's create an extension module called \samp{spam} (the favorite food
85of Monty Python fans...) and let's say we want to create a Python
Fred Drakeec9fbe91999-02-15 16:20:25 +000086interface to the C library function \cfunction{system()}.\footnote{An
Guido van Rossumb92112d1995-03-20 14:24:09 +000087interface for this function already exists in the standard module
Fred Draked7bb3031998-03-03 17:52:07 +000088\module{os} --- it was chosen as a simple and straightfoward example.}
Guido van Rossumb92112d1995-03-20 14:24:09 +000089This function takes a null-terminated character string as argument and
90returns an integer. We want this function to be callable from Python
91as follows:
92
Fred Drake1e11a5c1998-02-13 07:11:32 +000093\begin{verbatim}
94>>> import spam
95>>> status = spam.system("ls -l")
96\end{verbatim}
97
Fred Drake54fd8452000-04-03 04:54:28 +000098Begin by creating a file \file{spammodule.c}. (Historically, if a
Fred Drakeec9fbe91999-02-15 16:20:25 +000099module is called \samp{spam}, the C file containing its implementation
Guido van Rossumb92112d1995-03-20 14:24:09 +0000100is called \file{spammodule.c}; if the module name is very long, like
101\samp{spammify}, the module name can be just \file{spammify.c}.)
102
103The first line of our file can be:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000104
Fred Drake1e11a5c1998-02-13 07:11:32 +0000105\begin{verbatim}
Fred Drake54fd8452000-04-03 04:54:28 +0000106#include <Python.h>
Fred Drake1e11a5c1998-02-13 07:11:32 +0000107\end{verbatim}
108
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000109which pulls in the Python API (you can add a comment describing the
110purpose of the module and a copyright notice if you like).
111
Guido van Rossumb92112d1995-03-20 14:24:09 +0000112All 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.
114For convenience, and since they are used extensively by the Python
115interpreter, \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
Fred Draked7bb3031998-03-03 17:52:07 +0000118system, it declares the functions \cfunction{malloc()},
119\cfunction{free()} and \cfunction{realloc()} directly.
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000120
Fred Drakeec9fbe91999-02-15 16:20:25 +0000121The next thing we add to our module file is the C function that will
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000122be called when the Python expression \samp{spam.system(\var{string})}
Guido van Rossumb92112d1995-03-20 14:24:09 +0000123is evaluated (we'll see shortly how it ends up being called):
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000124
Fred Drake1e11a5c1998-02-13 07:11:32 +0000125\begin{verbatim}
126static PyObject *
127spam_system(self, args)
128 PyObject *self;
129 PyObject *args;
130{
131 char *command;
132 int sts;
Fred Drakea0dbddf1998-04-02 06:50:02 +0000133
Fred Drake1e11a5c1998-02-13 07:11:32 +0000134 if (!PyArg_ParseTuple(args, "s", &command))
135 return NULL;
136 sts = system(command);
137 return Py_BuildValue("i", sts);
138}
139\end{verbatim}
140
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000141There is a straightforward translation from the argument list in
Guido van Rossumb92112d1995-03-20 14:24:09 +0000142Python (e.g.\ the single expression \code{"ls -l"}) to the arguments
Fred Drakeec9fbe91999-02-15 16:20:25 +0000143passed to the C function. The C function always has two arguments,
Guido van Rossumb92112d1995-03-20 14:24:09 +0000144conventionally named \var{self} and \var{args}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000145
Fred Drakeec9fbe91999-02-15 16:20:25 +0000146The \var{self} argument is only used when the C function implements a
Fred Drake9226d8e1999-02-22 14:55:46 +0000147built-in method, not a function. In the example, \var{self} will
148always be a \NULL{} pointer, since we are defining a function, not a
149method. (This is done so that the interpreter doesn't have to
150understand two different types of C functions.)
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000151
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000152The \var{args} argument will be a pointer to a Python tuple object
Guido van Rossumb92112d1995-03-20 14:24:09 +0000153containing the arguments. Each item of the tuple corresponds to an
154argument in the call's argument list. The arguments are Python
Fred Drakeec9fbe91999-02-15 16:20:25 +0000155objects --- in order to do anything with them in our C function we have
156to convert them to C values. The function \cfunction{PyArg_ParseTuple()}
157in the Python API checks the argument types and converts them to C
Guido van Rossumb92112d1995-03-20 14:24:09 +0000158values. It uses a template string to determine the required types of
Fred Drakeec9fbe91999-02-15 16:20:25 +0000159the arguments as well as the types of the C variables into which to
Guido van Rossumb92112d1995-03-20 14:24:09 +0000160store the converted values. More about this later.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000161
Fred Drake3da06a61998-02-26 18:49:12 +0000162\cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have
Guido van Rossumb92112d1995-03-20 14:24:09 +0000163the right type and its components have been stored in the variables
164whose addresses are passed. It returns false (zero) if an invalid
165argument list was passed. In the latter case it also raises an
Fred Drake54fd8452000-04-03 04:54:28 +0000166appropriate exception so the calling function can return
Fred Drake0fd82681998-01-09 05:39:38 +0000167\NULL{} immediately (as we saw in the example).
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000168
169
Fred Drake5e8aa541998-11-16 18:34:07 +0000170\section{Intermezzo: Errors and Exceptions
171 \label{errors}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000172
173An important convention throughout the Python interpreter is the
174following: when a function fails, it should set an exception condition
Fred Drake0fd82681998-01-09 05:39:38 +0000175and return an error value (usually a \NULL{} pointer). Exceptions
Guido van Rossumb92112d1995-03-20 14:24:09 +0000176are stored in a static global variable inside the interpreter; if this
Fred Drake0fd82681998-01-09 05:39:38 +0000177variable is \NULL{} no exception has occurred. A second global
Guido van Rossumb92112d1995-03-20 14:24:09 +0000178variable stores the ``associated value'' of the exception (the second
Fred Draked7bb3031998-03-03 17:52:07 +0000179argument to \keyword{raise}). A third variable contains the stack
Guido van Rossumb92112d1995-03-20 14:24:09 +0000180traceback in case the error originated in Python code. These three
Fred Drakeec9fbe91999-02-15 16:20:25 +0000181variables are the C equivalents of the Python variables
Fred Drakef9918f21999-02-05 18:30:49 +0000182\code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see
Fred Drake9fa76f11999-11-10 16:01:43 +0000183the section on module \module{sys} in the
184\citetitle[../lib/lib.html]{Python Library Reference}). It is
185important to know about them to understand how errors are passed
186around.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000187
Guido van Rossumb92112d1995-03-20 14:24:09 +0000188The Python API defines a number of functions to set various types of
189exceptions.
190
Fred Draked7bb3031998-03-03 17:52:07 +0000191The most common one is \cfunction{PyErr_SetString()}. Its arguments
Fred Drakeec9fbe91999-02-15 16:20:25 +0000192are an exception object and a C string. The exception object is
Fred Draked7bb3031998-03-03 17:52:07 +0000193usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The
Fred Drakeec9fbe91999-02-15 16:20:25 +0000194C string indicates the cause of the error and is converted to a
Fred Draked7bb3031998-03-03 17:52:07 +0000195Python string object and stored as the ``associated value'' of the
196exception.
Guido van Rossumb92112d1995-03-20 14:24:09 +0000197
Fred Draked7bb3031998-03-03 17:52:07 +0000198Another useful function is \cfunction{PyErr_SetFromErrno()}, which only
Guido van Rossumb92112d1995-03-20 14:24:09 +0000199takes an exception argument and constructs the associated value by
Fred Drake54fd8452000-04-03 04:54:28 +0000200inspection of the global variable \cdata{errno}. The most
Fred Draked7bb3031998-03-03 17:52:07 +0000201general function is \cfunction{PyErr_SetObject()}, which takes two object
Guido van Rossumb92112d1995-03-20 14:24:09 +0000202arguments, the exception and its associated value. You don't need to
Fred Draked7bb3031998-03-03 17:52:07 +0000203\cfunction{Py_INCREF()} the objects passed to any of these functions.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000204
205You can test non-destructively whether an exception has been set with
Fred Draked7bb3031998-03-03 17:52:07 +0000206\cfunction{PyErr_Occurred()}. This returns the current exception object,
Fred Drake0fd82681998-01-09 05:39:38 +0000207or \NULL{} if no exception has occurred. You normally don't need
Fred Draked7bb3031998-03-03 17:52:07 +0000208to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a
Guido van Rossumb92112d1995-03-20 14:24:09 +0000209function call, since you should be able to tell from the return value.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000210
Guido van Rossumd16ddb61996-12-13 02:38:17 +0000211When a function \var{f} that calls another function \var{g} detects
Guido van Rossumb92112d1995-03-20 14:24:09 +0000212that the latter fails, \var{f} should itself return an error value
Fred Drake33698f81999-02-16 23:06:32 +0000213(e.g.\ \NULL{} or \code{-1}). It should \emph{not} call one of the
Fred Draked7bb3031998-03-03 17:52:07 +0000214\cfunction{PyErr_*()} functions --- one has already been called by \var{g}.
Guido van Rossumb92112d1995-03-20 14:24:09 +0000215\var{f}'s caller is then supposed to also return an error indication
Fred Draked7bb3031998-03-03 17:52:07 +0000216to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()},
Guido van Rossumb92112d1995-03-20 14:24:09 +0000217and so on --- the most detailed cause of the error was already
218reported by the function that first detected it. Once the error
219reaches the Python interpreter's main loop, this aborts the currently
220executing Python code and tries to find an exception handler specified
221by the Python programmer.
Guido van Rossum6938f061994-08-01 12:22:53 +0000222
223(There are situations where a module can actually give a more detailed
Fred Draked7bb3031998-03-03 17:52:07 +0000224error message by calling another \cfunction{PyErr_*()} function, and in
Guido van Rossumb92112d1995-03-20 14:24:09 +0000225such cases it is fine to do so. As a general rule, however, this is
226not necessary, and can cause information about the cause of the error
227to be lost: most operations can fail for a variety of reasons.)
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000228
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000229To ignore an exception set by a function call that failed, the exception
Fred Draked7bb3031998-03-03 17:52:07 +0000230condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}.
Fred Drakeec9fbe91999-02-15 16:20:25 +0000231The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000232want to pass the error on to the interpreter but wants to handle it
Fred Drake33698f81999-02-16 23:06:32 +0000233completely by itself (e.g.\ by trying something else or pretending
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000234nothing happened).
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000235
Fred Drake54fd8452000-04-03 04:54:28 +0000236Every failing \cfunction{malloc()} call must be turned into an
Fred Draked7bb3031998-03-03 17:52:07 +0000237exception --- the direct caller of \cfunction{malloc()} (or
238\cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and
239return a failure indicator itself. All the object-creating functions
Fred Drake54fd8452000-04-03 04:54:28 +0000240(for example, \cfunction{PyInt_FromLong()}) already do this, so this
241note is only relevant to those who call \cfunction{malloc()} directly.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000242
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000243Also note that, with the important exception of
Fred Drake3da06a61998-02-26 18:49:12 +0000244\cfunction{PyArg_ParseTuple()} and friends, functions that return an
Guido van Rossumb92112d1995-03-20 14:24:09 +0000245integer status usually return a positive value or zero for success and
246\code{-1} for failure, like \UNIX{} system calls.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000247
Fred Draked7bb3031998-03-03 17:52:07 +0000248Finally, be careful to clean up garbage (by making
249\cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects
250you have already created) when you return an error indicator!
Guido van Rossum6938f061994-08-01 12:22:53 +0000251
252The choice of which exception to raise is entirely yours. There are
Fred Drakeec9fbe91999-02-15 16:20:25 +0000253predeclared C objects corresponding to all built-in Python exceptions,
Fred Drakeabfd7d61999-02-16 17:34:51 +0000254e.g.\ \cdata{PyExc_ZeroDivisionError}, which you can use directly. Of
Guido van Rossumb92112d1995-03-20 14:24:09 +0000255course, you should choose exceptions wisely --- don't use
Fred Draked7bb3031998-03-03 17:52:07 +0000256\cdata{PyExc_TypeError} to mean that a file couldn't be opened (that
257should probably be \cdata{PyExc_IOError}). If something's wrong with
Fred Drake3da06a61998-02-26 18:49:12 +0000258the argument list, the \cfunction{PyArg_ParseTuple()} function usually
Fred Draked7bb3031998-03-03 17:52:07 +0000259raises \cdata{PyExc_TypeError}. If you have an argument whose value
Fred Drakedc12ec81999-03-09 18:36:55 +0000260must be in a particular range or must satisfy other conditions,
Fred Draked7bb3031998-03-03 17:52:07 +0000261\cdata{PyExc_ValueError} is appropriate.
Guido van Rossum6938f061994-08-01 12:22:53 +0000262
263You can also define a new exception that is unique to your module.
264For this, you usually declare a static object variable at the
265beginning of your file, e.g.
266
Fred Drake1e11a5c1998-02-13 07:11:32 +0000267\begin{verbatim}
268static PyObject *SpamError;
269\end{verbatim}
270
Guido van Rossum6938f061994-08-01 12:22:53 +0000271and initialize it in your module's initialization function
Fred Drake33698f81999-02-16 23:06:32 +0000272(\cfunction{initspam()}) with an exception object, e.g.\ (leaving out
Fred Draked7bb3031998-03-03 17:52:07 +0000273the error checking for now):
Guido van Rossum6938f061994-08-01 12:22:53 +0000274
Fred Drake1e11a5c1998-02-13 07:11:32 +0000275\begin{verbatim}
276void
277initspam()
278{
279 PyObject *m, *d;
Fred Drakea0dbddf1998-04-02 06:50:02 +0000280
Fred Drake1e11a5c1998-02-13 07:11:32 +0000281 m = Py_InitModule("spam", SpamMethods);
282 d = PyModule_GetDict(m);
Fred Draked7bb3031998-03-03 17:52:07 +0000283 SpamError = PyErr_NewException("spam.error", NULL, NULL);
Fred Drake1e11a5c1998-02-13 07:11:32 +0000284 PyDict_SetItemString(d, "error", SpamError);
285}
286\end{verbatim}
287
Guido van Rossumb92112d1995-03-20 14:24:09 +0000288Note that the Python name for the exception object is
Fred Draked7bb3031998-03-03 17:52:07 +0000289\exception{spam.error}. The \cfunction{PyErr_NewException()} function
290may create either a string or class, depending on whether the
Fred Drake9fa76f11999-11-10 16:01:43 +0000291\programopt{-X} flag was passed to the interpreter. If
292\programopt{-X} was used, \cdata{SpamError} will be a string object,
293otherwise 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
Fred Draked7bb3031998-03-03 17:52:07 +0000296Exceptions.''
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000297
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000298
Fred Drake5e8aa541998-11-16 18:34:07 +0000299\section{Back to the Example
300 \label{backToExample}}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000301
302Going back to our example function, you should now be able to
303understand this statement:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000304
Fred Drake1e11a5c1998-02-13 07:11:32 +0000305\begin{verbatim}
306 if (!PyArg_ParseTuple(args, "s", &command))
307 return NULL;
308\end{verbatim}
309
Fred Drake0fd82681998-01-09 05:39:38 +0000310It returns \NULL{} (the error indicator for functions returning
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000311object pointers) if an error is detected in the argument list, relying
Fred Drake3da06a61998-02-26 18:49:12 +0000312on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000313string value of the argument has been copied to the local variable
Fred Draked7bb3031998-03-03 17:52:07 +0000314\cdata{command}. This is a pointer assignment and you are not supposed
Fred Drakeec9fbe91999-02-15 16:20:25 +0000315to modify the string to which it points (so in Standard C, the variable
Fred Draked7bb3031998-03-03 17:52:07 +0000316\cdata{command} should properly be declared as \samp{const char
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000317*command}).
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000318
Fred Draked7bb3031998-03-03 17:52:07 +0000319The next statement is a call to the \UNIX{} function
320\cfunction{system()}, passing it the string we just got from
321\cfunction{PyArg_ParseTuple()}:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000322
Fred Drake1e11a5c1998-02-13 07:11:32 +0000323\begin{verbatim}
324 sts = system(command);
325\end{verbatim}
326
Fred Draked7bb3031998-03-03 17:52:07 +0000327Our \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
Fred Drakeec9fbe91999-02-15 16:20:25 +0000331arbitrary number of C values, and returns a new Python object.
Fred Draked7bb3031998-03-03 17:52:07 +0000332More info on \cfunction{Py_BuildValue()} is given later.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000333
Fred Drake1e11a5c1998-02-13 07:11:32 +0000334\begin{verbatim}
335 return Py_BuildValue("i", sts);
336\end{verbatim}
337
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000338In this case, it will return an integer object. (Yes, even integers
339are objects on the heap in Python!)
Guido van Rossum6938f061994-08-01 12:22:53 +0000340
Fred Drakeec9fbe91999-02-15 16:20:25 +0000341If you have a C function that returns no useful argument (a function
Fred Draked7bb3031998-03-03 17:52:07 +0000342returning \ctype{void}), the corresponding Python function must return
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000343\code{None}. You need this idiom to do so:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000344
Fred Drake1e11a5c1998-02-13 07:11:32 +0000345\begin{verbatim}
346 Py_INCREF(Py_None);
347 return Py_None;
348\end{verbatim}
349
Fred Drakeec9fbe91999-02-15 16:20:25 +0000350\cdata{Py_None} is the C name for the special Python object
Fred Drakea0dbddf1998-04-02 06:50:02 +0000351\code{None}. It is a genuine Python object rather than a \NULL{}
352pointer, which means ``error'' in most contexts, as we have seen.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000353
354
Fred Drake5e8aa541998-11-16 18:34:07 +0000355\section{The Module's Method Table and Initialization Function
356 \label{methodTable}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000357
Fred Draked7bb3031998-03-03 17:52:07 +0000358I promised to show how \cfunction{spam_system()} is called from Python
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000359programs. First, we need to list its name and address in a ``method
360table'':
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000361
Fred Drake1e11a5c1998-02-13 07:11:32 +0000362\begin{verbatim}
363static PyMethodDef SpamMethods[] = {
364 ...
365 {"system", spam_system, METH_VARARGS},
366 ...
367 {NULL, NULL} /* Sentinel */
368};
369\end{verbatim}
370
Fred Drake0fd82681998-01-09 05:39:38 +0000371Note the third entry (\samp{METH_VARARGS}). This is a flag telling
Fred Drakeec9fbe91999-02-15 16:20:25 +0000372the interpreter the calling convention to be used for the C
Fred Drake0fd82681998-01-09 05:39:38 +0000373function. It should normally always be \samp{METH_VARARGS} or
Fred Drakea0dbddf1998-04-02 06:50:02 +0000374\samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an
Fred Drake3da06a61998-02-26 18:49:12 +0000375obsolete variant of \cfunction{PyArg_ParseTuple()} is used.
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000376
Fred Drakeb6e50321998-02-04 20:26:31 +0000377When using only \samp{METH_VARARGS}, the function should expect
378the Python-level parameters to be passed in as a tuple acceptable for
379parsing via \cfunction{PyArg_ParseTuple()}; more information on this
380function is provided below.
381
Fred Drake2d545232000-05-10 20:33:18 +0000382The \constant{METH_KEYWORDS} bit may be set in the third field if
383keyword arguments should be passed to the function. In this case, the
384C function should accept a third \samp{PyObject *} parameter which
385will be a dictionary of keywords. Use
386\cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to
387such a function.
Fred Drake0fd82681998-01-09 05:39:38 +0000388
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000389The method table must be passed to the interpreter in the module's
Fred Drake2d545232000-05-10 20:33:18 +0000390initialization function. The initialization function must be named
391\cfunction{init\var{name}()}, where \var{name} is the name of the
392module, and should be the only non-\keyword{static} item defined in
393the module file:
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000394
Fred Drake1e11a5c1998-02-13 07:11:32 +0000395\begin{verbatim}
396void
397initspam()
398{
399 (void) Py_InitModule("spam", SpamMethods);
400}
401\end{verbatim}
402
Fred Drake65e69002000-05-10 20:36:34 +0000403Note that for \Cpp, this method must be declared \code{extern "C"}.
404
Fred Draked7bb3031998-03-03 17:52:07 +0000405When the Python program imports module \module{spam} for the first
Fred Drake54fd8452000-04-03 04:54:28 +0000406time, \cfunction{initspam()} is called. (See below for comments about
407embedding Python.) It calls
Fred Draked7bb3031998-03-03 17:52:07 +0000408\cfunction{Py_InitModule()}, which creates a ``module object'' (which
409is inserted in the dictionary \code{sys.modules} under the key
410\code{"spam"}), and inserts built-in function objects into the newly
411created module based upon the table (an array of \ctype{PyMethodDef}
412structures) that was passed as its second argument.
413\cfunction{Py_InitModule()} returns a pointer to the module object
414that it creates (which is unused here). It aborts with a fatal error
415if the module could not be initialized satisfactorily, so the caller
416doesn't need to check for errors.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000417
Fred Drake54fd8452000-04-03 04:54:28 +0000418When embedding Python, the \cfunction{initspam()} function is not
419called automatically unless there's an entry in the
420\cdata{_PyImport_Inittab} table. The easiest way to handle this is to
421statically initialize your statically-linked modules by directly
422calling \cfunction{initspam()} after the call to
423\cfunction{Py_Initialize()} or \cfunction{PyMac_Initialize()}:
424
425\begin{verbatim}
426int main(int argc, char **argv)
427{
428 /* Pass argv[0] to the Python interpreter */
429 Py_SetProgramName(argv[0]);
430
431 /* Initialize the Python interpreter. Required. */
432 Py_Initialize();
433
434 /* Add a static module */
435 initspam();
436\end{verbatim}
437
Fred Drake4dc1a6d2000-10-02 22:38:09 +0000438An example may be found in the file \file{Demo/embed/demo.c} in the
Fred Drake54fd8452000-04-03 04:54:28 +0000439Python source distribution.
440
Fred Drakea48a0831999-06-18 19:17:28 +0000441\strong{Note:} Removing entries from \code{sys.modules} or importing
442compiled modules into multiple interpreters within a process (or
443following a \cfunction{fork()} without an intervening
444\cfunction{exec()}) can create problems for some extension modules.
445Extension module authors should exercise caution when initializing
446internal data structures.
Fred Drake4dc1a6d2000-10-02 22:38:09 +0000447Note also that the \function{reload()} function can be used with
448extension modules, and will call the module initialization function
449(\cfunction{initspam()} in the example), but will not load the module
450again if it was loaded from a dynamically loadable object file
451(\file{.so} on \UNIX, \file{.dll} on Windows).
Fred Drakea48a0831999-06-18 19:17:28 +0000452
Fred Drake54fd8452000-04-03 04:54:28 +0000453A more substantial example module is included in the Python source
454distribution as \file{Modules/xxmodule.c}. This file may be used as a
455template or simply read as an example. The \program{modulator.py}
456script included in the source distribution or Windows install provides
457a simple graphical user interface for declaring the functions and
458objects which a module should implement, and can generate a template
459which can be filled in. The script lives in the
460\file{Tools/modulator/} directory; see the \file{README} file there
461for more information.
462
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000463
Fred Drake5e8aa541998-11-16 18:34:07 +0000464\section{Compilation and Linkage
465 \label{compilation}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000466
Guido van Rossumb92112d1995-03-20 14:24:09 +0000467There are two more things to do before you can use your new extension:
468compiling and linking it with the Python system. If you use dynamic
469loading, the details depend on the style of dynamic loading your
Fred Drake54fd8452000-04-03 04:54:28 +0000470system 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
Guido van Rossum6938f061994-08-01 12:22:53 +0000474
475If you can't use dynamic loading, or if you want to make your module a
476permanent part of the Python interpreter, you will have to change the
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000477configuration setup and rebuild the interpreter. Luckily, this is
478very simple: just place your file (\file{spammodule.c} for example) in
Fred Drakea4a90dd1999-04-29 02:44:50 +0000479the \file{Modules/} directory of an unpacked source distribution, add
480a line to the file \file{Modules/Setup.local} describing your file:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000481
Fred Drake1e11a5c1998-02-13 07:11:32 +0000482\begin{verbatim}
483spam spammodule.o
484\end{verbatim}
485
Fred Draked7bb3031998-03-03 17:52:07 +0000486and rebuild the interpreter by running \program{make} in the toplevel
Fred Drakea4a90dd1999-04-29 02:44:50 +0000487directory. You can also run \program{make} in the \file{Modules/}
Fred Drakea0dbddf1998-04-02 06:50:02 +0000488subdirectory, but then you must first rebuild \file{Makefile}
Fred Draked7bb3031998-03-03 17:52:07 +0000489there by running `\program{make} Makefile'. (This is necessary each
490time you change the \file{Setup} file.)
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000491
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000492If your module requires additional libraries to link with, these can
Fred Drakea0dbddf1998-04-02 06:50:02 +0000493be listed on the line in the configuration file as well, for instance:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000494
Fred Drake1e11a5c1998-02-13 07:11:32 +0000495\begin{verbatim}
496spam spammodule.o -lX11
497\end{verbatim}
498
Fred Drakeec9fbe91999-02-15 16:20:25 +0000499\section{Calling Python Functions from C
Fred Drake5e8aa541998-11-16 18:34:07 +0000500 \label{callingPython}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000501
Fred Drakeec9fbe91999-02-15 16:20:25 +0000502So far we have concentrated on making C functions callable from
503Python. The reverse is also useful: calling Python functions from C.
Guido van Rossum6938f061994-08-01 12:22:53 +0000504This is especially the case for libraries that support so-called
Fred Drakeec9fbe91999-02-15 16:20:25 +0000505``callback'' functions. If a C interface makes use of callbacks, the
Guido van Rossum6938f061994-08-01 12:22:53 +0000506equivalent Python often needs to provide a callback mechanism to the
507Python programmer; the implementation will require calling the Python
Fred Drakeec9fbe91999-02-15 16:20:25 +0000508callback functions from a C callback. Other uses are also imaginable.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000509
510Fortunately, the Python interpreter is easily called recursively, and
Guido van Rossum6938f061994-08-01 12:22:53 +0000511there is a standard interface to call a Python function. (I won't
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000512dwell on how to call the Python parser with a particular string as
Guido van Rossumdb65a6c1993-11-05 17:11:16 +0000513input --- if you're interested, have a look at the implementation of
Fred Drake9fa76f11999-11-10 16:01:43 +0000514the \programopt{-c} command line option in \file{Python/pythonmain.c}
515from the Python source code.)
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000516
517Calling a Python function is easy. First, the Python program must
518somehow pass you the Python function object. You should provide a
519function (or some other interface) to do this. When this function is
520called, save a pointer to the Python function object (be careful to
Fred Drakedc12ec81999-03-09 18:36:55 +0000521\cfunction{Py_INCREF()} it!) in a global variable --- or wherever you
Fred Draked7bb3031998-03-03 17:52:07 +0000522see fit. For example, the following function might be part of a module
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000523definition:
524
Fred Drake1e11a5c1998-02-13 07:11:32 +0000525\begin{verbatim}
526static PyObject *my_callback = NULL;
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000527
Fred Drake1e11a5c1998-02-13 07:11:32 +0000528static PyObject *
Fred Drake54fd8452000-04-03 04:54:28 +0000529my_set_callback(dummy, args)
530 PyObject *dummy, *args;
Fred Drake1e11a5c1998-02-13 07:11:32 +0000531{
Fred Drake5e8aa541998-11-16 18:34:07 +0000532 PyObject *result = NULL;
533 PyObject *temp;
534
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;
539 }
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;
546 }
547 return result;
Fred Drake1e11a5c1998-02-13 07:11:32 +0000548}
549\end{verbatim}
550
Fred Drake5e8aa541998-11-16 18:34:07 +0000551This function must be registered with the interpreter using the
Fred Drake5f342ac1999-04-29 02:47:40 +0000552\constant{METH_VARARGS} flag; this is described in section
Fred Drake5e8aa541998-11-16 18:34:07 +0000553\ref{methodTable}, ``The Module's Method Table and Initialization
554Function.'' The \cfunction{PyArg_ParseTuple()} function and its
Fred Drake5f342ac1999-04-29 02:47:40 +0000555arguments are documented in section \ref{parseTuple}, ``Format Strings
Fred Drake5e8aa541998-11-16 18:34:07 +0000556for \cfunction{PyArg_ParseTuple()}.''
557
Fred Draked7bb3031998-03-03 17:52:07 +0000558The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()}
559increment/decrement the reference count of an object and are safe in
Fred Drake5e8aa541998-11-16 18:34:07 +0000560the presence of \NULL{} pointers (but note that \var{temp} will not be
Fred Drake5f342ac1999-04-29 02:47:40 +0000561\NULL{} in this context). More info on them in section
Fred Drake5e8aa541998-11-16 18:34:07 +0000562\ref{refcounts}, ``Reference Counts.''
Guido van Rossum6938f061994-08-01 12:22:53 +0000563
Fred Drakeec9fbe91999-02-15 16:20:25 +0000564Later, when it is time to call the function, you call the C function
Fred Draked7bb3031998-03-03 17:52:07 +0000565\cfunction{PyEval_CallObject()}. This function has two arguments, both
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000566pointers to arbitrary Python objects: the Python function, and the
567argument list. The argument list must always be a tuple object, whose
568length is the number of arguments. To call the Python function with
569no arguments, pass an empty tuple; to call it with one argument, pass
Fred Draked7bb3031998-03-03 17:52:07 +0000570a singleton tuple. \cfunction{Py_BuildValue()} returns a tuple when its
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000571format string consists of zero or more format codes between
572parentheses. For example:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000573
Fred Drake1e11a5c1998-02-13 07:11:32 +0000574\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000575 int arg;
576 PyObject *arglist;
577 PyObject *result;
578 ...
579 arg = 123;
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000580 ...
581 /* Time to call the callback */
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000582 arglist = Py_BuildValue("(i)", arg);
583 result = PyEval_CallObject(my_callback, arglist);
584 Py_DECREF(arglist);
Fred Drake1e11a5c1998-02-13 07:11:32 +0000585\end{verbatim}
586
Fred Draked7bb3031998-03-03 17:52:07 +0000587\cfunction{PyEval_CallObject()} returns a Python object pointer: this is
588the return value of the Python function. \cfunction{PyEval_CallObject()} is
Guido van Rossumb92112d1995-03-20 14:24:09 +0000589``reference-count-neutral'' with respect to its arguments. In the
Guido van Rossum6938f061994-08-01 12:22:53 +0000590example a new tuple was created to serve as the argument list, which
Fred Draked7bb3031998-03-03 17:52:07 +0000591is \cfunction{Py_DECREF()}-ed immediately after the call.
Guido van Rossum6938f061994-08-01 12:22:53 +0000592
Fred Draked7bb3031998-03-03 17:52:07 +0000593The return value of \cfunction{PyEval_CallObject()} is ``new'': either it
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000594is a brand new object, or it is an existing object whose reference
595count has been incremented. So, unless you want to save it in a
Fred Draked7bb3031998-03-03 17:52:07 +0000596global variable, you should somehow \cfunction{Py_DECREF()} the result,
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000597even (especially!) if you are not interested in its value.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000598
599Before you do this, however, it is important to check that the return
Fred Draked7bb3031998-03-03 17:52:07 +0000600value isn't \NULL{}. If it is, the Python function terminated by
Fred Drakeec9fbe91999-02-15 16:20:25 +0000601raising an exception. If the C code that called
Fred Draked7bb3031998-03-03 17:52:07 +0000602\cfunction{PyEval_CallObject()} is called from Python, it should now
603return an error indication to its Python caller, so the interpreter
604can print a stack trace, or the calling Python code can handle the
605exception. If this is not possible or desirable, the exception should
606be cleared by calling \cfunction{PyErr_Clear()}. For example:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000607
Fred Drake1e11a5c1998-02-13 07:11:32 +0000608\begin{verbatim}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000609 if (result == NULL)
610 return NULL; /* Pass error back */
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000611 ...use result...
612 Py_DECREF(result);
Fred Drake1e11a5c1998-02-13 07:11:32 +0000613\end{verbatim}
614
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000615Depending on the desired interface to the Python callback function,
Fred Draked7bb3031998-03-03 17:52:07 +0000616you may also have to provide an argument list to
617\cfunction{PyEval_CallObject()}. In some cases the argument list is
618also provided by the Python program, through the same interface that
619specified the callback function. It can then be saved and used in the
620same manner as the function object. In other cases, you may have to
621construct a new tuple to pass as the argument list. The simplest way
622to do this is to call \cfunction{Py_BuildValue()}. For example, if
623you want to pass an integral event code, you might use the following
624code:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000625
Fred Drake1e11a5c1998-02-13 07:11:32 +0000626\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000627 PyObject *arglist;
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000628 ...
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000629 arglist = Py_BuildValue("(l)", eventcode);
630 result = PyEval_CallObject(my_callback, arglist);
631 Py_DECREF(arglist);
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000632 if (result == NULL)
633 return NULL; /* Pass error back */
634 /* Here maybe use the result */
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000635 Py_DECREF(result);
Fred Drake1e11a5c1998-02-13 07:11:32 +0000636\end{verbatim}
637
Fred Draked7bb3031998-03-03 17:52:07 +0000638Note the placement of \samp{Py_DECREF(arglist)} immediately after the
639call, before the error check! Also note that strictly spoken this
640code is not complete: \cfunction{Py_BuildValue()} may run out of
641memory, and this should be checked.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000642
643
Fred Drake5e8aa541998-11-16 18:34:07 +0000644\section{Format Strings for \cfunction{PyArg_ParseTuple()}
645 \label{parseTuple}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000646
Fred Drake3da06a61998-02-26 18:49:12 +0000647The \cfunction{PyArg_ParseTuple()} function is declared as follows:
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000648
Fred Drake1e11a5c1998-02-13 07:11:32 +0000649\begin{verbatim}
650int PyArg_ParseTuple(PyObject *arg, char *format, ...);
651\end{verbatim}
652
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000653The \var{arg} argument must be a tuple object containing an argument
Fred Drakeec9fbe91999-02-15 16:20:25 +0000654list passed from Python to a C function. The \var{format} argument
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000655must be a format string, whose syntax is explained below. The
656remaining arguments must be addresses of variables whose type is
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000657determined by the format string. For the conversion to succeed, the
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000658\var{arg} object must match the format and the format must be
659exhausted.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000660
Fred Drake3da06a61998-02-26 18:49:12 +0000661Note that while \cfunction{PyArg_ParseTuple()} checks that the Python
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000662arguments have the required types, it cannot check the validity of the
Fred Drakeec9fbe91999-02-15 16:20:25 +0000663addresses of C variables passed to the call: if you make mistakes
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000664there, your code will probably crash or at least overwrite random bits
665in memory. So be careful!
666
667A format string consists of zero or more ``format units''. A format
668unit describes one Python object; it is usually a single character or
669a parenthesized sequence of format units. With a few exceptions, a
670format unit that is not a parenthesized sequence normally corresponds
Fred Drake3da06a61998-02-26 18:49:12 +0000671to a single address argument to \cfunction{PyArg_ParseTuple()}. In the
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000672following description, the quoted form is the format unit; the entry
673in (round) parentheses is the Python object type that matches the
Fred Drakeec9fbe91999-02-15 16:20:25 +0000674format unit; and the entry in [square] brackets is the type of the C
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000675variable(s) whose address should be passed. (Use the \samp{\&}
676operator to pass a variable's address.)
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000677
Fred Drake54fd8452000-04-03 04:54:28 +0000678Note that any Python object references which are provided to the
679caller are \emph{borrowed} references; do not decrement their
680reference count!
681
Guido van Rossumdb65a6c1993-11-05 17:11:16 +0000682\begin{description}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000683
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000684\item[\samp{s} (string or Unicode object) {[char *]}]
685Convert a Python string or Unicode object to a C pointer to a
686character string. You must not provide storage for the string
687itself; a pointer to an existing string is stored into the character
688pointer variable whose address you pass. The C string is
689null-terminated. The Python string must not contain embedded null
690bytes; if it does, a \exception{TypeError} exception is raised.
691Unicode objects are converted to C strings using the default
692encoding. If this conversion fails, an \exception{UnicodeError} is
693raised.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000694
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000695\item[\samp{s\#} (string, Unicode or any read buffer compatible object)
696{[char *, int]}]
697This variant on \samp{s} stores into two C variables, the first one a
698pointer to a character string, the second one its length. In this
699case the Python string may contain embedded null bytes. Unicode
Marc-André Lemburg3578b772000-09-21 21:08:08 +0000700objects pass back a pointer to the default encoded string version of the
701object if such a conversion is possible. All other read buffer
702compatible objects pass back a reference to the raw internal data
703representation.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000704
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000705\item[\samp{z} (string or \code{None}) {[char *]}]
706Like \samp{s}, but the Python object may also be \code{None}, in which
Fred Drakeec9fbe91999-02-15 16:20:25 +0000707case the C pointer is set to \NULL{}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000708
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000709\item[\samp{z\#} (string or \code{None} or any read buffer compatible object)
710{[char *, int]}]
Fred Draked7bb3031998-03-03 17:52:07 +0000711This is to \samp{s\#} as \samp{z} is to \samp{s}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000712
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000713\item[\samp{u} (Unicode object) {[Py_UNICODE *]}]
Fred Drake25871c02000-05-03 15:17:02 +0000714Convert a Python Unicode object to a C pointer to a null-terminated
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000715buffer of 16-bit Unicode (UTF-16) data. As with \samp{s}, there is no need
Fred Drake25871c02000-05-03 15:17:02 +0000716to provide storage for the Unicode data buffer; a pointer to the
717existing Unicode data is stored into the Py_UNICODE pointer variable whose
718address you pass.
719
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000720\item[\samp{u\#} (Unicode object) {[Py_UNICODE *, int]}]
Fred Drake25871c02000-05-03 15:17:02 +0000721This variant on \samp{u} stores into two C variables, the first one
722a pointer to a Unicode data buffer, the second one its length.
723
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000724\item[\samp{es} (string, Unicode object or character buffer compatible
725object) {[const char *encoding, char **buffer]}]
726This variant on \samp{s} is used for encoding Unicode and objects
727convertible to Unicode into a character buffer. It only works for
728encoded data without embedded \NULL{} bytes.
729
730The variant reads one C variable and stores into two C variables, the
731first one a pointer to an encoding name string (\var{encoding}), the
732second a pointer to a pointer to a character buffer (\var{**buffer},
733the buffer used for storing the encoded data) and the third one a
734pointer to an integer (\var{*buffer_length}, the buffer length).
735
736The encoding name must map to a registered codec. If set to \NULL{},
737the default encoding is used.
738
Fred Drake4e159452000-08-11 17:09:23 +0000739\cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000740size using \cfunction{PyMem_NEW()}, copy the encoded data into this
741buffer and adjust \var{*buffer} to reference the newly allocated
742storage. The caller is responsible for calling
743\cfunction{PyMem_Free()} to free the allocated buffer after usage.
744
745\item[\samp{es\#} (string, Unicode object or character buffer compatible
746object) {[const char *encoding, char **buffer, int *buffer_length]}]
747This variant on \samp{s\#} is used for encoding Unicode and objects
748convertible to Unicode into a character buffer. It reads one C
749variable and stores into two C variables, the first one a pointer to
750an encoding name string (\var{encoding}), the second a pointer to a
751pointer to a character buffer (\var{**buffer}, the buffer used for
752storing the encoded data) and the third one a pointer to an integer
753(\var{*buffer_length}, the buffer length).
754
755The encoding name must map to a registered codec. If set to \NULL{},
756the default encoding is used.
757
758There are two modes of operation:
759
760If \var{*buffer} points a \NULL{} pointer,
Fred Drake4e159452000-08-11 17:09:23 +0000761\cfunction{PyArg_ParseTuple()} will allocate a buffer of the needed
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000762size using \cfunction{PyMem_NEW()}, copy the encoded data into this
763buffer and adjust \var{*buffer} to reference the newly allocated
764storage. The caller is responsible for calling
765\cfunction{PyMem_Free()} to free the allocated buffer after usage.
766
767If \var{*buffer} points to a non-\NULL{} pointer (an already allocated
Fred Drake4e159452000-08-11 17:09:23 +0000768buffer), \cfunction{PyArg_ParseTuple()} will use this location as
Marc-André Lemburg8b9835c2000-08-03 19:38:07 +0000769buffer and interpret \var{*buffer_length} as buffer size. It will then
770copy the encoded data into the buffer and 0-terminate it. Buffer
771overflow is signalled with an exception.
772
773In both cases, \var{*buffer_length} is set to the length of the
774encoded data without the trailing 0-byte.
775
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000776\item[\samp{b} (integer) {[char]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000777Convert a Python integer to a tiny int, stored in a C \ctype{char}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000778
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000779\item[\samp{h} (integer) {[short int]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000780Convert a Python integer to a C \ctype{short int}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000781
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000782\item[\samp{i} (integer) {[int]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000783Convert a Python integer to a plain C \ctype{int}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000784
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000785\item[\samp{l} (integer) {[long int]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000786Convert a Python integer to a C \ctype{long int}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000787
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000788\item[\samp{c} (string of length 1) {[char]}]
789Convert a Python character, represented as a string of length 1, to a
Fred Drakeec9fbe91999-02-15 16:20:25 +0000790C \ctype{char}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000791
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000792\item[\samp{f} (float) {[float]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000793Convert a Python floating point number to a C \ctype{float}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000794
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000795\item[\samp{d} (float) {[double]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000796Convert a Python floating point number to a C \ctype{double}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000797
Fred Drakeb6e50321998-02-04 20:26:31 +0000798\item[\samp{D} (complex) {[Py_complex]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000799Convert a Python complex number to a C \ctype{Py_complex} structure.
Fred Drakeb6e50321998-02-04 20:26:31 +0000800
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000801\item[\samp{O} (object) {[PyObject *]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000802Store a Python object (without any conversion) in a C object pointer.
803The C program thus receives the actual object that was passed. The
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000804object's reference count is not increased. The pointer stored is not
Fred Drake0fd82681998-01-09 05:39:38 +0000805\NULL{}.
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000806
Fred Drake3fe985f1998-03-04 03:51:42 +0000807\item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000808Store 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
810Python type object, the second is the address of the C variable (of
Fred Draked7bb3031998-03-03 17:52:07 +0000811type \ctype{PyObject *}) into which the object pointer is stored.
Fred Drake54fd8452000-04-03 04:54:28 +0000812If the Python object does not have the required type,
813\exception{TypeError} is raised.
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000814
Fred Drake3fe985f1998-03-04 03:51:42 +0000815\item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +0000816Convert a Python object to a C variable through a \var{converter}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000817function. This takes two arguments: the first is a function, the
Fred Drakeec9fbe91999-02-15 16:20:25 +0000818second is the address of a C variable (of arbitrary type), converted
Fred Draked7bb3031998-03-03 17:52:07 +0000819to \ctype{void *}. The \var{converter} function in turn is called as
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000820follows:
821
Fred Drake82ac24f1999-07-02 14:29:14 +0000822\var{status}\code{ = }\var{converter}\code{(}\var{object}, \var{address}\code{);}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000823
824where \var{object} is the Python object to be converted and
Fred Draked7bb3031998-03-03 17:52:07 +0000825\var{address} is the \ctype{void *} argument that was passed to
826\cfunction{PyArg_ConvertTuple()}. The returned \var{status} should be
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000827\code{1} for a successful conversion and \code{0} if the conversion
828has failed. When the conversion fails, the \var{converter} function
829should raise an exception.
830
831\item[\samp{S} (string) {[PyStringObject *]}]
Guido van Rossum2474d681998-02-26 17:07:11 +0000832Like \samp{O} but requires that the Python object is a string object.
Fred Drake54fd8452000-04-03 04:54:28 +0000833Raises \exception{TypeError} if the object is not a string object.
834The C variable may also be declared as \ctype{PyObject *}.
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000835
Fred Drake25871c02000-05-03 15:17:02 +0000836\item[\samp{U} (Unicode string) {[PyUnicodeObject *]}]
837Like \samp{O} but requires that the Python object is a Unicode object.
838Raises \exception{TypeError} if the object is not a Unicode object.
839The C variable may also be declared as \ctype{PyObject *}.
840
Fred Drake8779f641999-08-27 15:28:15 +0000841\item[\samp{t\#} (read-only character buffer) {[char *, int]}]
842Like \samp{s\#}, but accepts any object which implements the read-only
843buffer interface. The \ctype{char *} variable is set to point to the
844first byte of the buffer, and the \ctype{int} is set to the length of
845the buffer. Only single-segment buffer objects are accepted;
846\exception{TypeError} is raised for all others.
847
848\item[\samp{w} (read-write character buffer) {[char *]}]
849Similar to \samp{s}, but accepts any object which implements the
850read-write buffer interface. The caller must determine the length of
851the buffer by other means, or use \samp{w\#} instead. Only
852single-segment buffer objects are accepted; \exception{TypeError} is
853raised for all others.
854
855\item[\samp{w\#} (read-write character buffer) {[char *, int]}]
856Like \samp{s\#}, but accepts any object which implements the
857read-write buffer interface. The \ctype{char *} variable is set to
858point to the first byte of the buffer, and the \ctype{int} is set to
859the length of the buffer. Only single-segment buffer objects are
860accepted; \exception{TypeError} is raised for all others.
861
Fred Drake3fe985f1998-03-04 03:51:42 +0000862\item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
Fred Drake29fb54f1999-02-18 03:50:01 +0000863The object must be a Python sequence whose length is the number of
864format units in \var{items}. The C arguments must correspond to the
865individual format units in \var{items}. Format units for sequences
866may be nested.
867
868\strong{Note:} Prior to Python version 1.5.2, this format specifier
869only accepted a tuple containing the individual parameters, not an
Fred Drake54fd8452000-04-03 04:54:28 +0000870arbitrary sequence. Code which previously caused
Fred Drake29fb54f1999-02-18 03:50:01 +0000871\exception{TypeError} to be raised here may now proceed without an
872exception. This is not expected to be a problem for existing code.
Guido van Rossumdb65a6c1993-11-05 17:11:16 +0000873
874\end{description}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000875
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000876It is possible to pass Python long integers where integers are
Fred Drake1aedbd81998-02-16 14:47:27 +0000877requested; however no proper range checking is done --- the most
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000878significant bits are silently truncated when the receiving field is
879too small to receive the value (actually, the semantics are inherited
Fred Drakedc12ec81999-03-09 18:36:55 +0000880from downcasts in C --- your mileage may vary).
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000881
882A few other characters have a meaning in a format string. These may
883not occur inside nested parentheses. They are:
884
885\begin{description}
886
887\item[\samp{|}]
888Indicates that the remaining arguments in the Python argument list are
Fred Drakeec9fbe91999-02-15 16:20:25 +0000889optional. The C variables corresponding to optional arguments should
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000890be initialized to their default value --- when an optional argument is
Fred Drake40e72f71998-03-03 19:37:38 +0000891not specified, \cfunction{PyArg_ParseTuple()} does not touch the contents
Fred Drakeec9fbe91999-02-15 16:20:25 +0000892of the corresponding C variable(s).
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000893
894\item[\samp{:}]
895The list of format units ends here; the string after the colon is used
896as the function name in error messages (the ``associated value'' of
Fred Drakedc12ec81999-03-09 18:36:55 +0000897the exception that \cfunction{PyArg_ParseTuple()} raises).
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000898
899\item[\samp{;}]
900The list of format units ends here; the string after the colon is used
901as the error message \emph{instead} of the default error message.
902Clearly, \samp{:} and \samp{;} mutually exclude each other.
903
904\end{description}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000905
906Some example calls:
907
Fred Drake0fd82681998-01-09 05:39:38 +0000908\begin{verbatim}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000909 int ok;
910 int i, j;
911 long k, l;
912 char *s;
913 int size;
914
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000915 ok = PyArg_ParseTuple(args, ""); /* No arguments */
Guido van Rossum6938f061994-08-01 12:22:53 +0000916 /* Python call: f() */
Fred Drake33698f81999-02-16 23:06:32 +0000917\end{verbatim}
Fred Drake0fd82681998-01-09 05:39:38 +0000918
Fred Drake33698f81999-02-16 23:06:32 +0000919\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000920 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000921 /* Possible Python call: f('whoops!') */
Fred Drake33698f81999-02-16 23:06:32 +0000922\end{verbatim}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000923
Fred Drake33698f81999-02-16 23:06:32 +0000924\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000925 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
Guido van Rossum6938f061994-08-01 12:22:53 +0000926 /* Possible Python call: f(1, 2, 'three') */
Fred Drake33698f81999-02-16 23:06:32 +0000927\end{verbatim}
Fred Drake0fd82681998-01-09 05:39:38 +0000928
Fred Drake33698f81999-02-16 23:06:32 +0000929\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000930 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000931 /* A pair of ints and a string, whose size is also returned */
Guido van Rossum7e924dd1997-02-10 16:51:52 +0000932 /* Possible Python call: f((1, 2), 'three') */
Fred Drake33698f81999-02-16 23:06:32 +0000933\end{verbatim}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000934
Fred Drake33698f81999-02-16 23:06:32 +0000935\begin{verbatim}
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000936 {
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000937 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) */
946 }
Fred Drake33698f81999-02-16 23:06:32 +0000947\end{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000948
Fred Drake33698f81999-02-16 23:06:32 +0000949\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000950 {
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000951 int left, top, right, bottom, h, v;
Guido van Rossum5049bcb1995-03-13 16:55:23 +0000952 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000953 &left, &top, &right, &bottom, &h, &v);
Fred Drakea0dbddf1998-04-02 06:50:02 +0000954 /* A rectangle and a point */
955 /* Possible Python call:
956 f(((0, 0), (400, 300)), (10, 10)) */
Guido van Rossum7a2dba21993-11-05 14:45:11 +0000957 }
Fred Drake33698f81999-02-16 23:06:32 +0000958\end{verbatim}
Fred Drakeb6e50321998-02-04 20:26:31 +0000959
Fred Drake33698f81999-02-16 23:06:32 +0000960\begin{verbatim}
Fred Drakeb6e50321998-02-04 20:26:31 +0000961 {
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) */
966 }
Fred Drake0fd82681998-01-09 05:39:38 +0000967\end{verbatim}
Fred Drakeb6e50321998-02-04 20:26:31 +0000968
969
Fred Drake5e8aa541998-11-16 18:34:07 +0000970\section{Keyword Parsing with \cfunction{PyArg_ParseTupleAndKeywords()}
971 \label{parseTupleAndKeywords}}
Fred Drakeb6e50321998-02-04 20:26:31 +0000972
973The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as
974follows:
975
Fred Drake1e11a5c1998-02-13 07:11:32 +0000976\begin{verbatim}
977int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
978 char *format, char **kwlist, ...);
979\end{verbatim}
Fred Drakeb6e50321998-02-04 20:26:31 +0000980
981The \var{arg} and \var{format} parameters are identical to those of the
982\cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter
983is the dictionary of keywords received as the third parameter from the
984Python runtime. The \var{kwlist} parameter is a \NULL{}-terminated
985list of strings which identify the parameters; the names are matched
986with the type information from \var{format} from left to right.
987
988\strong{Note:} Nested tuples cannot be parsed when using keyword
989arguments! Keyword parameters passed in which are not present in the
Fred Drakecd05ca91998-03-07 05:32:08 +0000990\var{kwlist} will cause \exception{TypeError} to be raised.
Fred Drakeb6e50321998-02-04 20:26:31 +0000991
992Here is an example module which uses keywords, based on an example by
Fred Drakea0dbddf1998-04-02 06:50:02 +0000993Geoff Philbrick (\email{philbrick@hks.com}):%
994\index{Philbrick, Geoff}
Fred Drakeb6e50321998-02-04 20:26:31 +0000995
996\begin{verbatim}
997#include <stdio.h>
998#include "Python.h"
999
1000static PyObject *
1001keywdarg_parrot(self, args, keywds)
1002 PyObject *self;
1003 PyObject *args;
1004 PyObject *keywds;
1005{
1006 int voltage;
1007 char *state = "a stiff";
1008 char *action = "voom";
1009 char *type = "Norwegian Blue";
1010
1011 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
1012
1013 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
1014 &voltage, &state, &action, &type))
1015 return NULL;
1016
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);
1020
1021 Py_INCREF(Py_None);
1022
1023 return Py_None;
1024}
1025
1026static PyMethodDef keywdarg_methods[] = {
Fred Drakedc12ec81999-03-09 18:36:55 +00001027 /* The cast of the function is necessary since PyCFunction values
1028 * only take two PyObject* parameters, and keywdarg_parrot() takes
1029 * three.
1030 */
Fred Drakeb6e50321998-02-04 20:26:31 +00001031 {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS},
1032 {NULL, NULL} /* sentinel */
1033};
1034
1035void
1036initkeywdarg()
1037{
1038 /* Create the module and add the functions */
Fred Drakecd05ca91998-03-07 05:32:08 +00001039 Py_InitModule("keywdarg", keywdarg_methods);
Fred Drakeb6e50321998-02-04 20:26:31 +00001040}
1041\end{verbatim}
1042
1043
Fred Drake5e8aa541998-11-16 18:34:07 +00001044\section{The \cfunction{Py_BuildValue()} Function
1045 \label{buildValue}}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001046
Fred Draked7bb3031998-03-03 17:52:07 +00001047This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001048declared as follows:
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001049
Fred Drake1e11a5c1998-02-13 07:11:32 +00001050\begin{verbatim}
1051PyObject *Py_BuildValue(char *format, ...);
1052\end{verbatim}
1053
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001054It recognizes a set of format units similar to the ones recognized by
Fred Draked7bb3031998-03-03 17:52:07 +00001055\cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001056function, not output) must not be pointers, just values. It returns a
Fred Drakeec9fbe91999-02-15 16:20:25 +00001057new Python object, suitable for returning from a C function called
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001058from Python.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001059
Fred Draked7bb3031998-03-03 17:52:07 +00001060One difference with \cfunction{PyArg_ParseTuple()}: while the latter
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001061requires its first argument to be a tuple (since Python argument lists
Fred Draked7bb3031998-03-03 17:52:07 +00001062are always represented as tuples internally),
1063\cfunction{Py_BuildValue()} does not always build a tuple. It builds
1064a tuple only if its format string contains two or more format units.
1065If the format string is empty, it returns \code{None}; if it contains
1066exactly one format unit, it returns whatever object is described by
1067that format unit. To force it to return a tuple of size 0 or one,
1068parenthesize the format string.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001069
Fred Drake2b9e1802000-06-28 15:32:29 +00001070When memory buffers are passed as parameters to supply data to build
1071objects, as for the \samp{s} and \samp{s\#} formats, the required data
1072is copied. Buffers provided by the caller are never referenced by the
Fred Drakeec105d02000-06-28 16:15:08 +00001073objects created by \cfunction{Py_BuildValue()}. In other words, if
1074your code invokes \cfunction{malloc()} and passes the allocated memory
1075to \cfunction{Py_BuildValue()}, your code is responsible for
1076calling \cfunction{free()} for that memory once
1077\cfunction{Py_BuildValue()} returns.
Fred Drake2b9e1802000-06-28 15:32:29 +00001078
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001079In the following description, the quoted form is the format unit; the
1080entry in (round) parentheses is the Python object type that the format
1081unit will return; and the entry in [square] brackets is the type of
Fred Drakeec9fbe91999-02-15 16:20:25 +00001082the C value(s) to be passed.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001083
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001084The characters space, tab, colon and comma are ignored in format
1085strings (but not within format units such as \samp{s\#}). This can be
1086used to make long format strings a tad more readable.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001087
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001088\begin{description}
1089
1090\item[\samp{s} (string) {[char *]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001091Convert a null-terminated C string to a Python object. If the C
Fred Drake2b9e1802000-06-28 15:32:29 +00001092string pointer is \NULL{}, \code{None} is used.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001093
1094\item[\samp{s\#} (string) {[char *, int]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001095Convert a C string and its length to a Python object. If the C string
Fred Drake0fd82681998-01-09 05:39:38 +00001096pointer is \NULL{}, the length is ignored and \code{None} is
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001097returned.
1098
1099\item[\samp{z} (string or \code{None}) {[char *]}]
1100Same as \samp{s}.
1101
1102\item[\samp{z\#} (string or \code{None}) {[char *, int]}]
1103Same as \samp{s\#}.
1104
Fred Drake3c3507f2000-04-28 14:43:33 +00001105\item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1106Convert a null-terminated buffer of Unicode (UCS-2) data to a Python
1107Unicode object. If the Unicode buffer pointer is \NULL,
1108\code{None} is returned.
1109
1110\item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1111Convert a Unicode (UCS-2) data buffer and its length to a Python
1112Unicode object. If the Unicode buffer pointer is \NULL, the length
1113is ignored and \code{None} is returned.
1114
Fred Drake25871c02000-05-03 15:17:02 +00001115\item[\samp{u} (Unicode string) {[Py_UNICODE *]}]
1116Convert a null-terminated buffer of Unicode (UCS-2) data to a Python Unicode
1117object. If the Unicode buffer pointer is \NULL{}, \code{None} is returned.
1118
1119\item[\samp{u\#} (Unicode string) {[Py_UNICODE *, int]}]
1120Convert a Unicode (UCS-2) data buffer and its length to a Python Unicode
1121object. If the Unicode buffer pointer is \NULL{}, the length is ignored and
1122\code{None} is returned.
1123
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001124\item[\samp{i} (integer) {[int]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001125Convert a plain C \ctype{int} to a Python integer object.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001126
1127\item[\samp{b} (integer) {[char]}]
1128Same as \samp{i}.
1129
1130\item[\samp{h} (integer) {[short int]}]
1131Same as \samp{i}.
1132
1133\item[\samp{l} (integer) {[long int]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001134Convert a C \ctype{long int} to a Python integer object.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001135
1136\item[\samp{c} (string of length 1) {[char]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001137Convert a C \ctype{int} representing a character to a Python string of
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001138length 1.
1139
1140\item[\samp{d} (float) {[double]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001141Convert a C \ctype{double} to a Python floating point number.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001142
1143\item[\samp{f} (float) {[float]}]
1144Same as \samp{d}.
1145
1146\item[\samp{O} (object) {[PyObject *]}]
1147Pass a Python object untouched (except for its reference count, which
Fred Drake0fd82681998-01-09 05:39:38 +00001148is incremented by one). If the object passed in is a \NULL{}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001149pointer, it is assumed that this was caused because the call producing
1150the argument found an error and set an exception. Therefore,
Fred Draked7bb3031998-03-03 17:52:07 +00001151\cfunction{Py_BuildValue()} will return \NULL{} but won't raise an
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001152exception. If no exception has been raised yet,
Fred Draked7bb3031998-03-03 17:52:07 +00001153\cdata{PyExc_SystemError} is set.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001154
1155\item[\samp{S} (object) {[PyObject *]}]
1156Same as \samp{O}.
1157
Fred Drake25871c02000-05-03 15:17:02 +00001158\item[\samp{U} (object) {[PyObject *]}]
1159Same as \samp{O}.
1160
Guido van Rossumd358afe1998-12-23 05:02:08 +00001161\item[\samp{N} (object) {[PyObject *]}]
1162Same as \samp{O}, except it doesn't increment the reference count on
1163the object. Useful when the object is created by a call to an object
1164constructor in the argument list.
1165
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001166\item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}]
1167Convert \var{anything} to a Python object through a \var{converter}
1168function. The function is called with \var{anything} (which should be
Fred Draked7bb3031998-03-03 17:52:07 +00001169compatible with \ctype{void *}) as its argument and should return a
Fred Drake0fd82681998-01-09 05:39:38 +00001170``new'' Python object, or \NULL{} if an error occurred.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001171
1172\item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001173Convert a sequence of C values to a Python tuple with the same number
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001174of items.
1175
1176\item[\samp{[\var{items}]} (list) {[\var{matching-items}]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001177Convert a sequence of C values to a Python list with the same number
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001178of items.
1179
1180\item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}]
Fred Drakeec9fbe91999-02-15 16:20:25 +00001181Convert a sequence of C values to a Python dictionary. Each pair of
1182consecutive C values adds one item to the dictionary, serving as key
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001183and value, respectively.
1184
1185\end{description}
1186
1187If there is an error in the format string, the
Fred Draked7bb3031998-03-03 17:52:07 +00001188\cdata{PyExc_SystemError} exception is raised and \NULL{} returned.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001189
1190Examples (to the left the call, to the right the resulting Python value):
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001191
Fred Drake1e11a5c1998-02-13 07:11:32 +00001192\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001193 Py_BuildValue("") None
1194 Py_BuildValue("i", 123) 123
Guido van Rossumf23e0fe1995-03-18 11:04:29 +00001195 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001196 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]
Guido van Rossumf23e0fe1995-03-18 11:04:29 +00001204 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))
Fred Drake1e11a5c1998-02-13 07:11:32 +00001208\end{verbatim}
1209
Fred Drake8e015171999-02-17 18:12:14 +00001210
Fred Drake5e8aa541998-11-16 18:34:07 +00001211\section{Reference Counts
1212 \label{refcounts}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001213
Fred Drakeec9fbe91999-02-15 16:20:25 +00001214In languages like C or \Cpp{}, the programmer is responsible for
1215dynamic allocation and deallocation of memory on the heap. In C,
Fred Draked7bb3031998-03-03 17:52:07 +00001216this 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
1219actually implemented using \cfunction{malloc()} and
1220\cfunction{free()}, so we'll restrict the following discussion to the
1221latter.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001222
Fred Draked7bb3031998-03-03 17:52:07 +00001223Every block of memory allocated with \cfunction{malloc()} should
1224eventually be returned to the pool of available memory by exactly one
1225call to \cfunction{free()}. It is important to call
1226\cfunction{free()} at the right time. If a block's address is
1227forgotten but \cfunction{free()} is not called for it, the memory it
1228occupies cannot be reused until the program terminates. This is
1229called 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
1231creates a conflict with re-use of the block through another
1232\cfunction{malloc()} call. This is called \dfn{using freed memory}.
1233It has the same bad consequences as referencing uninitialized data ---
1234core dumps, wrong results, mysterious crashes.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001235
1236Common causes of memory leaks are unusual paths through the code. For
1237instance, a function may allocate a block of memory, do some
1238calculation, and then free the block again. Now a change in the
1239requirements for the function may add a test to the calculation that
1240detects an error condition and can return prematurely from the
1241function. It's easy to forget to free the allocated memory block when
1242taking this premature exit, especially when it is added later to the
1243code. Such leaks, once introduced, often go undetected for a long
1244time: the error exit is taken only in a small fraction of all calls,
1245and most modern machines have plenty of virtual memory, so the leak
1246only becomes apparent in a long-running process that uses the leaking
1247function frequently. Therefore, it's important to prevent leaks from
1248happening by having a coding convention or strategy that minimizes
1249this kind of errors.
1250
Fred Draked7bb3031998-03-03 17:52:07 +00001251Since Python makes heavy use of \cfunction{malloc()} and
1252\cfunction{free()}, it needs a strategy to avoid memory leaks as well
1253as the use of freed memory. The chosen method is called
1254\dfn{reference counting}. The principle is simple: every object
1255contains a counter, which is incremented when a reference to the
1256object is stored somewhere, and which is decremented when a reference
1257to it is deleted. When the counter reaches zero, the last reference
1258to the object has been deleted and the object is freed.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001259
1260An alternative strategy is called \dfn{automatic garbage collection}.
1261(Sometimes, reference counting is also referred to as a garbage
1262collection strategy, hence my use of ``automatic'' to distinguish the
1263two.) The big advantage of automatic garbage collection is that the
Fred Draked7bb3031998-03-03 17:52:07 +00001264user doesn't need to call \cfunction{free()} explicitly. (Another claimed
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001265advantage is an improvement in speed or memory usage --- this is no
Fred Drakeec9fbe91999-02-15 16:20:25 +00001266hard fact however.) The disadvantage is that for C, there is no
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001267truly portable automatic garbage collector, while reference counting
Fred Draked7bb3031998-03-03 17:52:07 +00001268can be implemented portably (as long as the functions \cfunction{malloc()}
Fred Drakeec9fbe91999-02-15 16:20:25 +00001269and \cfunction{free()} are available --- which the C Standard guarantees).
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001270Maybe some day a sufficiently portable automatic garbage collector
Fred Drakeec9fbe91999-02-15 16:20:25 +00001271will be available for C. Until then, we'll have to live with
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001272reference counts.
1273
Fred Drake5e8aa541998-11-16 18:34:07 +00001274\subsection{Reference Counting in Python
1275 \label{refcountsInPython}}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001276
1277There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)},
1278which handle the incrementing and decrementing of the reference count.
Fred Draked7bb3031998-03-03 17:52:07 +00001279\cfunction{Py_DECREF()} also frees the object when the count reaches zero.
1280For flexibility, it doesn't call \cfunction{free()} directly --- rather, it
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001281makes a call through a function pointer in the object's \dfn{type
1282object}. For this purpose (and others), every object also contains a
1283pointer to its type object.
1284
1285The 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
1288object. An object's reference count is now defined as the number of
1289owned references to it. The owner of a reference is responsible for
Fred Draked7bb3031998-03-03 17:52:07 +00001290calling \cfunction{Py_DECREF()} when the reference is no longer
1291needed. Ownership of a reference can be transferred. There are three
1292ways to dispose of an owned reference: pass it on, store it, or call
1293\cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference
1294creates a memory leak.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001295
1296It is also possible to \dfn{borrow}\footnote{The metaphor of
1297``borrowing'' a reference is not completely correct: the owner still
1298has a copy of the reference.} a reference to an object. The borrower
Fred Draked7bb3031998-03-03 17:52:07 +00001299of a reference should not call \cfunction{Py_DECREF()}. The borrower must
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001300not hold on to the object longer than the owner from which it was
1301borrowed. Using a borrowed reference after the owner has disposed of
1302it risks using freed memory and should be avoided
1303completely.\footnote{Checking that the reference count is at least 1
1304\strong{does not work} --- the reference count itself could be in
1305freed memory and may thus be reused for another object!}
1306
1307The advantage of borrowing over owning a reference is that you don't
1308need to take care of disposing of the reference on all possible paths
1309through the code --- in other words, with a borrowed reference you
1310don't run the risk of leaking when a premature exit is taken. The
1311disadvantage of borrowing over leaking is that there are some subtle
1312situations where in seemingly correct code a borrowed reference can be
1313used after the owner from which it was borrowed has in fact disposed
1314of it.
1315
1316A borrowed reference can be changed into an owned reference by calling
Fred Draked7bb3031998-03-03 17:52:07 +00001317\cfunction{Py_INCREF()}. This does not affect the status of the owner from
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001318which the reference was borrowed --- it creates a new owned reference,
1319and gives full owner responsibilities (i.e., the new owner must
1320dispose of the reference properly, as well as the previous owner).
1321
Fred Drake8e015171999-02-17 18:12:14 +00001322
Fred Drake5e8aa541998-11-16 18:34:07 +00001323\subsection{Ownership Rules
1324 \label{ownershipRules}}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001325
1326Whenever an object reference is passed into or out of a function, it
1327is part of the function's interface specification whether ownership is
1328transferred with the reference or not.
1329
1330Most functions that return a reference to an object pass on ownership
1331with the reference. In particular, all functions whose function it is
Fred Draked7bb3031998-03-03 17:52:07 +00001332to create a new object, e.g.\ \cfunction{PyInt_FromLong()} and
1333\cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if in
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001334fact, in some cases, you don't receive a reference to a brand new
1335object, you still receive ownership of the reference. For instance,
Fred Draked7bb3031998-03-03 17:52:07 +00001336\cfunction{PyInt_FromLong()} maintains a cache of popular values and can
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001337return a reference to a cached item.
1338
1339Many functions that extract objects from other objects also transfer
1340ownership with the reference, for instance
Fred Draked7bb3031998-03-03 17:52:07 +00001341\cfunction{PyObject_GetAttrString()}. The picture is less clear, here,
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001342however, since a few common routines are exceptions:
Fred Draked7bb3031998-03-03 17:52:07 +00001343\cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()},
1344\cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()}
1345all return references that you borrow from the tuple, list or
1346dictionary.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001347
Fred Draked7bb3031998-03-03 17:52:07 +00001348The function \cfunction{PyImport_AddModule()} also returns a borrowed
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001349reference, even though it may actually create the object it returns:
1350this is possible because an owned reference to the object is stored in
1351\code{sys.modules}.
1352
1353When you pass an object reference into another function, in general,
1354the function borrows the reference from you --- if it needs to store
Fred Draked7bb3031998-03-03 17:52:07 +00001355it, it will use \cfunction{Py_INCREF()} to become an independent
1356owner. There are exactly two important exceptions to this rule:
1357\cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These
1358functions take over ownership of the item passed to them --- even if
1359they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't
Fred Drakea0dbddf1998-04-02 06:50:02 +00001360take over ownership --- they are ``normal.'')
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001361
Fred Drakeec9fbe91999-02-15 16:20:25 +00001362When a C function is called from Python, it borrows references to its
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001363arguments from the caller. The caller owns a reference to the object,
1364so the borrowed reference's lifetime is guaranteed until the function
1365returns. Only when such a borrowed reference must be stored or passed
1366on, it must be turned into an owned reference by calling
Fred Draked7bb3031998-03-03 17:52:07 +00001367\cfunction{Py_INCREF()}.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001368
Fred Drakeec9fbe91999-02-15 16:20:25 +00001369The object reference returned from a C function that is called from
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001370Python must be an owned reference --- ownership is tranferred from the
1371function to its caller.
1372
Fred Drake8e015171999-02-17 18:12:14 +00001373
Fred Drake5e8aa541998-11-16 18:34:07 +00001374\subsection{Thin Ice
1375 \label{thinIce}}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001376
1377There are a few situations where seemingly harmless use of a borrowed
1378reference can lead to problems. These all have to do with implicit
1379invocations of the interpreter, which can cause the owner of a
1380reference to dispose of it.
1381
1382The first and most important case to know about is using
Fred Draked7bb3031998-03-03 17:52:07 +00001383\cfunction{Py_DECREF()} on an unrelated object while borrowing a
1384reference to a list item. For instance:
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001385
Fred Drake1e11a5c1998-02-13 07:11:32 +00001386\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001387bug(PyObject *list) {
1388 PyObject *item = PyList_GetItem(list, 0);
Fred Drakea0dbddf1998-04-02 06:50:02 +00001389
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001390 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1391 PyObject_Print(item, stdout, 0); /* BUG! */
1392}
Fred Drake1e11a5c1998-02-13 07:11:32 +00001393\end{verbatim}
1394
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001395This function first borrows a reference to \code{list[0]}, then
1396replaces \code{list[1]} with the value \code{0}, and finally prints
1397the borrowed reference. Looks harmless, right? But it's not!
1398
Fred Draked7bb3031998-03-03 17:52:07 +00001399Let's follow the control flow into \cfunction{PyList_SetItem()}. The list
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001400owns references to all its items, so when item 1 is replaced, it has
1401to dispose of the original item 1. Now let's suppose the original
1402item 1 was an instance of a user-defined class, and let's further
Fred Draked7bb3031998-03-03 17:52:07 +00001403suppose that the class defined a \method{__del__()} method. If this
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001404class instance has a reference count of 1, disposing of it will call
Fred Draked7bb3031998-03-03 17:52:07 +00001405its \method{__del__()} method.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001406
Fred Draked7bb3031998-03-03 17:52:07 +00001407Since it is written in Python, the \method{__del__()} method can execute
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001408arbitrary Python code. Could it perhaps do something to invalidate
Fred Draked7bb3031998-03-03 17:52:07 +00001409the reference to \code{item} in \cfunction{bug()}? You bet! Assuming
1410that 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
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001413object, it would free the memory associated with it, thereby
1414invalidating \code{item}.
1415
1416The solution, once you know the source of the problem, is easy:
1417temporarily increment the reference count. The correct version of the
1418function reads:
1419
Fred Drake1e11a5c1998-02-13 07:11:32 +00001420\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001421no_bug(PyObject *list) {
1422 PyObject *item = PyList_GetItem(list, 0);
Fred Drakea0dbddf1998-04-02 06:50:02 +00001423
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001424 Py_INCREF(item);
1425 PyList_SetItem(list, 1, PyInt_FromLong(0L));
1426 PyObject_Print(item, stdout, 0);
1427 Py_DECREF(item);
1428}
Fred Drake1e11a5c1998-02-13 07:11:32 +00001429\end{verbatim}
1430
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001431This is a true story. An older version of Python contained variants
Fred Drakeec9fbe91999-02-15 16:20:25 +00001432of this bug and someone spent a considerable amount of time in a C
Fred Draked7bb3031998-03-03 17:52:07 +00001433debugger to figure out why his \method{__del__()} methods would fail...
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001434
1435The second case of problems with a borrowed reference is a variant
1436involving threads. Normally, multiple threads in the Python
1437interpreter can't get in each other's way, because there is a global
1438lock protecting Python's entire object space. However, it is possible
1439to 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
1442calls, to let other threads use the CPU while waiting for the I/O to
1443complete. Obviously, the following function has the same problem as
1444the previous one:
1445
Fred Drake1e11a5c1998-02-13 07:11:32 +00001446\begin{verbatim}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001447bug(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! */
1453}
Fred Drake1e11a5c1998-02-13 07:11:32 +00001454\end{verbatim}
1455
Fred Drake8e015171999-02-17 18:12:14 +00001456
Fred Drake5e8aa541998-11-16 18:34:07 +00001457\subsection{NULL Pointers
1458 \label{nullPointers}}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001459
Fred Drakea0dbddf1998-04-02 06:50:02 +00001460In general, functions that take object references as arguments do not
Fred Drake0fd82681998-01-09 05:39:38 +00001461expect you to pass them \NULL{} pointers, and will dump core (or
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001462cause later core dumps) if you do so. Functions that return object
Fred Drake0fd82681998-01-09 05:39:38 +00001463references generally return \NULL{} only to indicate that an
1464exception occurred. The reason for not testing for \NULL{}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001465arguments is that functions often pass the objects they receive on to
Fred Drake0fd82681998-01-09 05:39:38 +00001466other function --- if each function were to test for \NULL{},
Fred Drake1739be52000-06-30 17:58:34 +00001467there would be a lot of redundant tests and the code would run more
1468slowly.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001469
Fred Drakee743fd01998-11-24 17:07:29 +00001470It is better to test for \NULL{} only at the ``source'', i.e.\ when a
1471pointer that may be \NULL{} is received, e.g.\ from
Fred Draked7bb3031998-03-03 17:52:07 +00001472\cfunction{malloc()} or from a function that may raise an exception.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001473
Fred Draked7bb3031998-03-03 17:52:07 +00001474The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()}
Fred Drakea0dbddf1998-04-02 06:50:02 +00001475do not check for \NULL{} pointers --- however, their variants
Fred Draked7bb3031998-03-03 17:52:07 +00001476\cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do.
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001477
1478The macros for checking for a particular object type
Fred Drake0fd82681998-01-09 05:39:38 +00001479(\code{Py\var{type}_Check()}) don't check for \NULL{} pointers ---
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001480again, there is much code that calls several of these in a row to test
1481an object against various different expected types, and this would
Fred Drake0fd82681998-01-09 05:39:38 +00001482generate redundant tests. There are no variants with \NULL{}
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001483checking.
1484
Fred Drakeec9fbe91999-02-15 16:20:25 +00001485The C function calling mechanism guarantees that the argument list
1486passed to C functions (\code{args} in the examples) is never
Fred Drake52e2d511999-04-05 21:26:37 +00001487\NULL{} --- in fact it guarantees that it is always a tuple.\footnote{
1488These guarantees don't hold when you use the ``old'' style
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001489calling convention --- this is still found in much existing code.}
1490
Fred Drake0fd82681998-01-09 05:39:38 +00001491It is a severe error to ever let a \NULL{} pointer ``escape'' to
Fred Drake1739be52000-06-30 17:58:34 +00001492the Python user.
1493
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.
Guido van Rossumdb65a6c1993-11-05 17:11:16 +00001499
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001500
Fred Drake5e8aa541998-11-16 18:34:07 +00001501\section{Writing Extensions in \Cpp{}
1502 \label{cplusplus}}
Guido van Rossumdb65a6c1993-11-05 17:11:16 +00001503
Guido van Rossum16d6e711994-08-08 12:30:22 +00001504It is possible to write extension modules in \Cpp{}. Some restrictions
Guido van Rossumed39cd01995-10-08 00:17:19 +00001505apply. If the main program (the Python interpreter) is compiled and
Fred Drakeec9fbe91999-02-15 16:20:25 +00001506linked by the C compiler, global or static objects with constructors
Guido van Rossumed39cd01995-10-08 00:17:19 +00001507cannot be used. This is not a problem if the main program is linked
Guido van Rossumafcd5891998-02-05 19:59:39 +00001508by the \Cpp{} compiler. Functions that will be called by the
1509Python interpreter (in particular, module initalization functions)
1510have to be declared using \code{extern "C"}.
Guido van Rossumdb65a6c1993-11-05 17:11:16 +00001511It is unnecessary to enclose the Python header files in
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001512\code{extern "C" \{...\}} --- they use this form already if the symbol
Fred Drake0fd82681998-01-09 05:39:38 +00001513\samp{__cplusplus} is defined (all recent \Cpp{} compilers define this
Guido van Rossum5049bcb1995-03-13 16:55:23 +00001514symbol).
Guido van Rossum7a2dba21993-11-05 14:45:11 +00001515
Fred Drakee743fd01998-11-24 17:07:29 +00001516
Fred Drakeec9fbe91999-02-15 16:20:25 +00001517\section{Providing a C API for an Extension Module
1518 \label{using-cobjects}}
1519\sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr}
Fred Drakee743fd01998-11-24 17:07:29 +00001520
Fred Drakeec9fbe91999-02-15 16:20:25 +00001521Many extension modules just provide new functions and types to be
1522used from Python, but sometimes the code in an extension module can
1523be useful for other extension modules. For example, an extension
1524module could implement a type ``collection'' which works like lists
1525without order. Just like the standard Python list type has a C API
1526which permits extension modules to create and manipulate lists, this
1527new collection type should have a set of C functions for direct
1528manipulation from other extension modules.
1529
1530At first sight this seems easy: just write the functions (without
1531declaring them \keyword{static}, of course), provide an appropriate
1532header file, and document the C API. And in fact this would work if
1533all extension modules were always linked statically with the Python
1534interpreter. When modules are used as shared libraries, however, the
1535symbols defined in one module may not be visible to another module.
1536The details of visibility depend on the operating system; some systems
1537use one global namespace for the Python interpreter and all extension
Fred Drake33698f81999-02-16 23:06:32 +00001538modules (e.g.\ Windows), whereas others require an explicit list of
1539imported symbols at module link time (e.g.\ AIX), or offer a choice of
Fred Drakeec9fbe91999-02-15 16:20:25 +00001540different strategies (most Unices). And even if symbols are globally
1541visible, the module whose functions one wishes to call might not have
1542been loaded yet!
1543
1544Portability therefore requires not to make any assumptions about
1545symbol visibility. This means that all symbols in extension modules
1546should be declared \keyword{static}, except for the module's
1547initialization function, in order to avoid name clashes with other
1548extension modules (as discussed in section~\ref{methodTable}). And it
1549means that symbols that \emph{should} be accessible from other
1550extension modules must be exported in a different way.
1551
1552Python provides a special mechanism to pass C-level information (i.e.
1553pointers) from one extension module to another one: CObjects.
1554A 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
1556they can be passed around like any other Python object. In particular,
1557they can be assigned to a name in an extension module's namespace.
1558Other extension modules can then import this module, retrieve the
1559value of this name, and then retrieve the pointer from the CObject.
1560
1561There are many ways in which CObjects can be used to export the C API
1562of an extension module. Each name could get its own CObject, or all C
1563API pointers could be stored in an array whose address is published in
1564a CObject. And the various tasks of storing and retrieving the pointers
1565can be distributed in different ways between the module providing the
1566code and the client modules.
1567
1568The following example demonstrates an approach that puts most of the
1569burden on the writer of the exporting module, which is appropriate
1570for commonly used library modules. It stores all C API pointers
1571(just one in the example!) in an array of \ctype{void} pointers which
1572becomes the value of a CObject. The header file corresponding to
1573the module provides a macro that takes care of importing the module
1574and retrieving its C API pointers; client modules only have to call
1575this macro before accessing the C API.
1576
1577The exporting module is a modification of the \module{spam} module from
1578section~\ref{simpleExample}. The function \function{spam.system()}
1579does not call the C library function \cfunction{system()} directly,
1580but a function \cfunction{PySpam_System()}, which would of course do
1581something more complicated in reality (such as adding ``spam'' to
1582every command). This function \cfunction{PySpam_System()} is also
1583exported to other extension modules.
1584
1585The function \cfunction{PySpam_System()} is a plain C function,
1586declared \keyword{static} like everything else:
1587
1588\begin{verbatim}
1589static int
1590PySpam_System(command)
1591 char *command;
1592{
1593 return system(command);
1594}
1595\end{verbatim}
1596
1597The function \cfunction{spam_system()} is modified in a trivial way:
1598
1599\begin{verbatim}
1600static PyObject *
1601spam_system(self, args)
1602 PyObject *self;
1603 PyObject *args;
1604{
1605 char *command;
1606 int sts;
1607
1608 if (!PyArg_ParseTuple(args, "s", &command))
1609 return NULL;
1610 sts = PySpam_System(command);
1611 return Py_BuildValue("i", sts);
1612}
1613\end{verbatim}
1614
1615In the beginning of the module, right after the line
Fred Drake8e015171999-02-17 18:12:14 +00001616
Fred Drakeec9fbe91999-02-15 16:20:25 +00001617\begin{verbatim}
1618#include "Python.h"
1619\end{verbatim}
Fred Drake8e015171999-02-17 18:12:14 +00001620
Fred Drakeec9fbe91999-02-15 16:20:25 +00001621two more lines must be added:
Fred Drake8e015171999-02-17 18:12:14 +00001622
Fred Drakeec9fbe91999-02-15 16:20:25 +00001623\begin{verbatim}
1624#define SPAM_MODULE
1625#include "spammodule.h"
1626\end{verbatim}
1627
1628The \code{\#define} is used to tell the header file that it is being
1629included in the exporting module, not a client module. Finally,
1630the module's initialization function must take care of initializing
1631the C API pointer array:
Fred Drake8e015171999-02-17 18:12:14 +00001632
Fred Drakeec9fbe91999-02-15 16:20:25 +00001633\begin{verbatim}
1634void
1635initspam()
1636{
1637 PyObject *m, *d;
1638 static void *PySpam_API[PySpam_API_pointers];
1639 PyObject *c_api_object;
1640 m = Py_InitModule("spam", SpamMethods);
1641
1642 /* Initialize the C API pointer array */
1643 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1644
1645 /* Create a CObject containing the API pointer array's address */
1646 c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL);
1647
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);
1651}
1652\end{verbatim}
1653
1654Note that \code{PySpam_API} is declared \code{static}; otherwise
1655the pointer array would disappear when \code{initspam} terminates!
1656
1657The bulk of the work is in the header file \file{spammodule.h},
1658which looks like this:
1659
1660\begin{verbatim}
1661#ifndef Py_SPAMMODULE_H
1662#define Py_SPAMMODULE_H
1663#ifdef __cplusplus
1664extern "C" {
1665#endif
1666
1667/* Header file for spammodule */
1668
1669/* C API functions */
1670#define PySpam_System_NUM 0
1671#define PySpam_System_RETURN int
Greg Steinc2844af2000-07-09 16:27:33 +00001672#define PySpam_System_PROTO (char *command)
Fred Drakeec9fbe91999-02-15 16:20:25 +00001673
1674/* Total number of C API pointers */
1675#define PySpam_API_pointers 1
1676
1677
1678#ifdef SPAM_MODULE
1679/* This section is used when compiling spammodule.c */
1680
1681static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1682
1683#else
1684/* This section is used in modules that use spammodule's API */
1685
1686static void **PySpam_API;
1687
1688#define PySpam_System \
1689 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1690
1691#define import_spam() \
1692{ \
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); \
1699 } \
1700 } \
1701}
1702
1703#endif
1704
1705#ifdef __cplusplus
1706}
1707#endif
1708
1709#endif /* !defined(Py_SPAMMODULE_H */
1710\end{verbatim}
1711
1712All that a client module must do in order to have access to the
1713function \cfunction{PySpam_System()} is to call the function (or
1714rather macro) \cfunction{import_spam()} in its initialization
1715function:
1716
1717\begin{verbatim}
1718void
1719initclient()
1720{
1721 PyObject *m;
1722
1723 Py_InitModule("client", ClientMethods);
1724 import_spam();
1725}
1726\end{verbatim}
1727
1728The main disadvantage of this approach is that the file
1729\file{spammodule.h} is rather complicated. However, the
1730basic structure is the same for each function that is
1731exported, so it has to be learned only once.
1732
1733Finally it should be mentioned that CObjects offer additional
1734functionality, which is especially useful for memory allocation and
1735deallocation of the pointer stored in a CObject. The details
Fred Drake9fa76f11999-11-10 16:01:43 +00001736are described in the \citetitle[../api/api.html]{Python/C API
1737Reference Manual} in the section ``CObjects'' and in the
1738implementation of CObjects (files \file{Include/cobject.h} and
1739\file{Objects/cobject.c} in the Python source code distribution).
Fred Drakeec9fbe91999-02-15 16:20:25 +00001740
1741
1742\chapter{Building C and \Cpp{} Extensions on \UNIX{}
Fred Drake3de61bc1999-02-16 21:14:16 +00001743 \label{building-on-unix}}
Fred Drakee743fd01998-11-24 17:07:29 +00001744
Fred Drake33698f81999-02-16 23:06:32 +00001745\sectionauthor{Jim Fulton}{jim@Digicool.com}
Fred Drakee743fd01998-11-24 17:07:29 +00001746
1747
1748%The make file make file, building C extensions on Unix
1749
1750
1751Starting in Python 1.4, Python provides a special make file for
1752building make files for building dynamically-linked extensions and
1753custom interpreters. The make file make file builds a make file
1754that reflects various system variables determined by configure when
1755the Python interpreter was built, so people building module's don't
1756have to resupply these settings. This vastly simplifies the process
1757of building extensions and custom interpreters on Unix systems.
1758
1759The make file make file is distributed as the file
1760\file{Misc/Makefile.pre.in} in the Python source distribution. The
1761first step in building extensions or custom interpreters is to copy
1762this make file to a development directory containing extension module
1763source.
1764
1765The make file make file, \file{Makefile.pre.in} uses metadata
1766provided in a file named \file{Setup}. The format of the \file{Setup}
1767file is the same as the \file{Setup} (or \file{Setup.in}) file
1768provided in the \file{Modules/} directory of the Python source
Fred Drake33698f81999-02-16 23:06:32 +00001769distribution. The \file{Setup} file contains variable definitions:
Fred Drakee743fd01998-11-24 17:07:29 +00001770
1771\begin{verbatim}
1772EC=/projects/ExtensionClass
1773\end{verbatim}
1774
1775and module description lines. It can also contain blank lines and
1776comment lines that start with \character{\#}.
1777
1778A module description line includes a module name, source files,
1779options, variable references, and other input files, such
Fred Drake54fd8452000-04-03 04:54:28 +00001780as libraries or object files. Consider a simple example:
Fred Drakee743fd01998-11-24 17:07:29 +00001781
1782\begin{verbatim}
1783ExtensionClass ExtensionClass.c
1784\end{verbatim}
1785
1786This is the simplest form of a module definition line. It defines a
Fred Drake8e015171999-02-17 18:12:14 +00001787module, \module{ExtensionClass}, which has a single source file,
Fred Drakee743fd01998-11-24 17:07:29 +00001788\file{ExtensionClass.c}.
1789
Fred Drake8e015171999-02-17 18:12:14 +00001790This slightly more complex example uses an \strong{-I} option to
1791specify an include directory:
Fred Drakee743fd01998-11-24 17:07:29 +00001792
1793\begin{verbatim}
Fred Drake8e015171999-02-17 18:12:14 +00001794EC=/projects/ExtensionClass
Fred Drakee743fd01998-11-24 17:07:29 +00001795cPersistence cPersistence.c -I$(EC)
Fred Drake8e015171999-02-17 18:12:14 +00001796\end{verbatim} % $ <-- bow to font lock
Fred Drakee743fd01998-11-24 17:07:29 +00001797
1798This example also illustrates the format for variable references.
1799
1800For systems that support dynamic linking, the \file{Setup} file should
1801begin:
1802
1803\begin{verbatim}
1804*shared*
1805\end{verbatim}
1806
1807to indicate that the modules defined in \file{Setup} are to be built
Fred Drakedc12ec81999-03-09 18:36:55 +00001808as dynamically linked modules. A line containing only \samp{*static*}
1809can be used to indicate the subsequently listed modules should be
1810statically linked.
Fred Drakee743fd01998-11-24 17:07:29 +00001811
1812Here is a complete \file{Setup} file for building a
1813\module{cPersistent} module:
1814
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*
1819
1820# We need the path to the directory containing the ExtensionClass
1821# include file.
1822EC=/projects/ExtensionClass
1823cPersistence cPersistence.c -I$(EC)
Fred Drake8e015171999-02-17 18:12:14 +00001824\end{verbatim} % $ <-- bow to font lock
Fred Drakee743fd01998-11-24 17:07:29 +00001825
1826After the \file{Setup} file has been created, \file{Makefile.pre.in}
1827is run with the \samp{boot} target to create a make file:
1828
1829\begin{verbatim}
1830make -f Makefile.pre.in boot
1831\end{verbatim}
1832
1833This creates the file, Makefile. To build the extensions, simply
1834run the created make file:
1835
1836\begin{verbatim}
1837make
1838\end{verbatim}
1839
1840It's not necessary to re-run \file{Makefile.pre.in} if the
1841\file{Setup} file is changed. The make file automatically rebuilds
1842itself if the \file{Setup} file changes.
1843
Fred Drake8e015171999-02-17 18:12:14 +00001844
1845\section{Building Custom Interpreters \label{custom-interps}}
Fred Drakee743fd01998-11-24 17:07:29 +00001846
1847The make file built by \file{Makefile.pre.in} can be run with the
1848\samp{static} target to build an interpreter:
1849
1850\begin{verbatim}
1851make static
1852\end{verbatim}
1853
1854Any modules defined in the Setup file before the \samp{*shared*} line
1855will be statically linked into the interpreter. Typically, a
1856\samp{*shared*} line is omitted from the Setup file when a custom
1857interpreter is desired.
1858
Fred Drake8e015171999-02-17 18:12:14 +00001859
1860\section{Module Definition Options \label{module-defn-options}}
Fred Drakee743fd01998-11-24 17:07:29 +00001861
1862Several compiler options are supported:
1863
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}}
Fred Drake33698f81999-02-16 23:06:32 +00001868 \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}}
Fred Drakee743fd01998-11-24 17:07:29 +00001870 \lineii{-l\var{lib}}{Link a library, \var{lib}}
1871 \lineii{-U\var{name}}{Undefine a macro}
1872\end{tableii}
1873
1874Other compiler options can be included (snuck in) by putting them
Fred Drakedc12ec81999-03-09 18:36:55 +00001875in variables.
Fred Drakee743fd01998-11-24 17:07:29 +00001876
1877Source files can include files with \file{.c}, \file{.C}, \file{.cc},
Fred Drake8e015171999-02-17 18:12:14 +00001878\file{.cpp}, \file{.cxx}, and \file{.c++} extensions.
Fred Drakee743fd01998-11-24 17:07:29 +00001879
Fred Drake8e015171999-02-17 18:12:14 +00001880Other input files include files with \file{.a}, \file{.o}, \file{.sl},
1881and \file{.so} extensions.
Fred Drakee743fd01998-11-24 17:07:29 +00001882
1883
Fred Drake8e015171999-02-17 18:12:14 +00001884\section{Example \label{module-defn-example}}
Fred Drakee743fd01998-11-24 17:07:29 +00001885
1886Here is a more complicated example from \file{Modules/Setup.in}:
1887
1888\begin{verbatim}
1889GMP=/ufs/guido/src/gmp
1890mpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a
1891\end{verbatim}
1892
1893which could also be written as:
1894
1895\begin{verbatim}
1896mpz mpzmodule.c -I$(GMP) -L$(GMP) -lgmp
1897\end{verbatim}
1898
1899
1900\section{Distributing your extension modules
1901 \label{distributing}}
1902
1903When distributing your extension modules in source form, make sure to
1904include 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}.
1907Distributing a \file{Setup.in} file makes it easy for people to
1908customize the \file{Setup} file while keeping the original in
1909\file{Setup.in}.
1910
1911It is a good idea to include a copy of \file{Makefile.pre.in} for
1912people who do not have a source distribution of Python.
1913
1914Do not distribute a make file. People building your modules
Fred Drake8e015171999-02-17 18:12:14 +00001915should use \file{Makefile.pre.in} to build their own make file. A
1916\file{README} file included in the package should provide simple
1917instructions to perform the build.
Fred Drakee743fd01998-11-24 17:07:29 +00001918
Fred Drake33698f81999-02-16 23:06:32 +00001919Work is being done to make building and installing Python extensions
1920easier for all platforms; this work in likely to supplant the current
1921approach at some point in the future. For more information or to
1922participate in the effort, refer to
1923\url{http://www.python.org/sigs/distutils-sig/} on the Python Web
1924site.
1925
Fred Drakee743fd01998-11-24 17:07:29 +00001926
Fred Drake3de61bc1999-02-16 21:14:16 +00001927\chapter{Building C and \Cpp{} Extensions on Windows
Fred Drake33698f81999-02-16 23:06:32 +00001928 \label{building-on-windows}}
Fred Drake3de61bc1999-02-16 21:14:16 +00001929
1930
1931This chapter briefly explains how to create a Windows extension module
Fred Drake33698f81999-02-16 23:06:32 +00001932for Python using Microsoft Visual \Cpp{}, and follows with more
1933detailed background information on how it works. The explanatory
1934material is useful for both the Windows programmer learning to build
Fred Drake54fd8452000-04-03 04:54:28 +00001935Python extensions and the \UNIX{} programmer interested in producing
Fred Drake33698f81999-02-16 23:06:32 +00001936software which can be successfully built on both \UNIX{} and Windows.
1937
Fred Drake8e015171999-02-17 18:12:14 +00001938
Fred Drake33698f81999-02-16 23:06:32 +00001939\section{A Cookbook Approach \label{win-cookbook}}
1940
1941\sectionauthor{Neil Schemenauer}{neil_schemenauer@transcanada.com}
1942
1943This section provides a recipe for building a Python extension on
1944Windows.
Fred Drake3de61bc1999-02-16 21:14:16 +00001945
1946Grab the binary installer from \url{http://www.python.org/} and
1947install Python. The binary installer has all of the required header
1948files except for \file{config.h}.
1949
1950Get the source distribution and extract it into a convenient location.
1951Copy the \file{config.h} from the \file{PC/} directory into the
1952\file{include/} directory created by the installer.
1953
1954Create a \file{Setup} file for your extension module, as described in
Fred Drake54fd8452000-04-03 04:54:28 +00001955chapter \ref{building-on-unix}.
Fred Drake3de61bc1999-02-16 21:14:16 +00001956
1957Get David Ascher's \file{compile.py} script from
Fred Drakec0fcbc11999-04-29 02:30:04 +00001958\url{http://starship.python.net/crew/da/compile/}. Run the script to
Fred Drake3de61bc1999-02-16 21:14:16 +00001959create Microsoft Visual \Cpp{} project files.
1960
Fred Drake54fd8452000-04-03 04:54:28 +00001961Open the DSW file in Visual \Cpp{} and select \strong{Build}.
Fred Drake3de61bc1999-02-16 21:14:16 +00001962
1963If your module creates a new type, you may have trouble with this line:
1964
1965\begin{verbatim}
1966 PyObject_HEAD_INIT(&PyType_Type)
1967\end{verbatim}
1968
1969Change it to:
1970
1971\begin{verbatim}
1972 PyObject_HEAD_INIT(NULL)
1973\end{verbatim}
1974
1975and add the following to the module initialization function:
1976
1977\begin{verbatim}
1978 MyObject_Type.ob_type = &PyType_Type;
1979\end{verbatim}
1980
1981Refer to section 3 of the Python FAQ
1982(\url{http://www.python.org/doc/FAQ.html}) for details on why you must
1983do this.
1984
1985
Fred Drake33698f81999-02-16 23:06:32 +00001986\section{Differences Between \UNIX{} and Windows
1987 \label{dynamic-linking}}
1988\sectionauthor{Chris Phoenix}{cphoenix@best.com}
1989
1990
1991\UNIX{} and Windows use completely different paradigms for run-time
1992loading of code. Before you try to build a module that can be
1993dynamically loaded, be aware of how your system works.
1994
Fred Drake54fd8452000-04-03 04:54:28 +00001995In \UNIX{}, a shared object (\file{.so}) file contains code to be used by the
Fred Drake33698f81999-02-16 23:06:32 +00001996program, and also the names of functions and data that it expects to
1997find in the program. When the file is joined to the program, all
1998references to those functions and data in the file's code are changed
1999to point to the actual locations in the program where the functions
2000and data are placed in memory. This is basically a link operation.
2001
2002In Windows, a dynamic-link library (\file{.dll}) file has no dangling
2003references. Instead, an access to functions or data goes through a
2004lookup table. So the DLL code does not have to be fixed up at runtime
2005to refer to the program's memory; instead, the code already uses the
2006DLL's lookup table, and the lookup table is modified at runtime to
2007point to the functions and data.
2008
2009In \UNIX{}, there is only one type of library file (\file{.a}) which
2010contains code from several object files (\file{.o}). During the link
2011step to create a shared object file (\file{.so}), the linker may find
2012that it doesn't know where an identifier is defined. The linker will
2013look for it in the object files in the libraries; if it finds it, it
2014will include all the code from that object file.
2015
2016In Windows, there are two types of library, a static library and an
2017import library (both called \file{.lib}). A static library is like a
2018\UNIX{} \file{.a} file; it contains code to be included as necessary.
2019An import library is basically used only to reassure the linker that a
2020certain identifier is legal, and will be present in the program when
2021the DLL is loaded. So the linker uses the information from the
2022import library to build the lookup table for using identifiers that
2023are not included in the DLL. When an application or a DLL is linked,
2024an import library may be generated, which will need to be used for all
2025future DLLs that depend on the symbols in the application or DLL.
2026
2027Suppose you are building two dynamic-load modules, B and C, which should
2028share 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
2030cause it to be included twice, so that B and C would each have their
2031own 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
2033C. \file{A.lib} does not contain code; it just contains information
2034which will be used at runtime to access A's code.
2035
2036In Windows, using an import library is sort of like using \samp{import
2037spam}; it gives you access to spam's names, but does not create a
2038separate copy. On \UNIX{}, linking with a library is more like
2039\samp{from spam import *}; it does create a separate copy.
2040
2041
2042\section{Using DLLs in Practice \label{win-dlls}}
2043\sectionauthor{Chris Phoenix}{cphoenix@best.com}
2044
2045Windows Python is built in Microsoft Visual \Cpp{}; using other
2046compilers may or may not work (though Borland seems to). The rest of
2047this section is MSV\Cpp{} specific.
2048
2049When creating DLLs in Windows, you must pass \file{python15.lib} to
2050the linker. To build two DLLs, spam and ni (which uses C functions
2051found in spam), you could use these commands:
2052
2053\begin{verbatim}
2054cl /LD /I/python/include spam.c ../libs/python15.lib
2055cl /LD /I/python/include ni.c spam.lib ../libs/python15.lib
2056\end{verbatim}
2057
2058The first command created three files: \file{spam.obj},
2059\file{spam.dll} and \file{spam.lib}. \file{Spam.dll} does not contain
2060any Python functions (such as \cfunction{PyArg_ParseTuple()}), but it
2061does know how to find the Python code thanks to \file{python15.lib}.
2062
2063The second command created \file{ni.dll} (and \file{.obj} and
2064\file{.lib}), which knows how to find the necessary functions from
2065spam, and also from the Python executable.
2066
2067Not every identifier is exported to the lookup table. If you want any
2068other modules (including Python) to be able to see your identifiers,
2069you have to say \samp{_declspec(dllexport)}, as in \samp{void
2070_declspec(dllexport) initspam(void)} or \samp{PyObject
2071_declspec(dllexport) *NiGetSpamData(void)}.
2072
2073Developer Studio will throw in a lot of import libraries that you do
2074not really need, adding about 100K to your executable. To get rid of
2075them, 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.
2078
2079
Fred Drake5e8aa541998-11-16 18:34:07 +00002080\chapter{Embedding Python in Another Application
2081 \label{embedding}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002082
2083Embedding Python is similar to extending it, but not quite. The
2084difference is that when you extend Python, the main program of the
Guido van Rossum16d6e711994-08-08 12:30:22 +00002085application is still the Python interpreter, while if you embed
Guido van Rossumdb65a6c1993-11-05 17:11:16 +00002086Python, the main program may have nothing to do with Python ---
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002087instead, some parts of the application occasionally call the Python
2088interpreter to run some Python code.
2089
2090So if you are embedding Python, you are providing your own main
2091program. One of the things this main program has to do is initialize
2092the Python interpreter. At the very least, you have to call the
Fred Drake54fd8452000-04-03 04:54:28 +00002093function \cfunction{Py_Initialize()} (on MacOS, call
2094\cfunction{PyMac_Initialize()} instead). There are optional calls to
Fred Draked7bb3031998-03-03 17:52:07 +00002095pass command line arguments to Python. Then later you can call the
2096interpreter from any part of the application.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002097
2098There are several different ways to call the interpreter: you can pass
Fred Draked7bb3031998-03-03 17:52:07 +00002099a string containing Python statements to
2100\cfunction{PyRun_SimpleString()}, or you can pass a stdio file pointer
2101and a file name (for identification in error messages only) to
2102\cfunction{PyRun_SimpleFile()}. You can also call the lower-level
2103operations described in the previous chapters to construct and use
2104Python objects.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002105
2106A simple demo of embedding Python can be found in the directory
Fred Drake295fb431999-02-16 17:29:42 +00002107\file{Demo/embed/} of the source distribution.
Guido van Rossumdb65a6c1993-11-05 17:11:16 +00002108
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002109
Fred Drake5e8aa541998-11-16 18:34:07 +00002110\section{Embedding Python in \Cpp{}
2111 \label{embeddingInCplusplus}}
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002112
Guido van Rossum16d6e711994-08-08 12:30:22 +00002113It is also possible to embed Python in a \Cpp{} program; precisely how this
2114is done will depend on the details of the \Cpp{} system used; in general you
2115will need to write the main program in \Cpp{}, and use the \Cpp{} compiler
2116to compile and link your program. There is no need to recompile Python
2117itself using \Cpp{}.
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002118
Fred Drake1c258032000-09-08 22:54:53 +00002119
2120\section{Linking Requirements
2121 \label{link-reqs}}
2122
2123While the \program{configure} script shipped with the Python sources
2124will correctly build Python to export the symbols needed by
2125dynamically linked extensions, this is not automatically inherited by
2126applications which embed the Python library statically, at least on
2127\UNIX. This is an issue when the application is linked to the static
2128runtime library (\file{libpython.a}) and needs to load dynamic
2129extensions (implemented as \file{.so} files).
2130
2131The problem is that some entry points are defined by the Python
2132runtime solely for extension modules to use. If the embedding
2133application does not use any of these entry points, some linkers will
2134not include those entries in the symbol table of the finished
2135executable. Some additional options are needed to inform the linker
2136not to remove these symbols.
2137
2138Determining the right options to use for any given platform can be
2139quite difficult, but fortunately the Python configuration already has
2140those values. To retrieve them from an installed Python interpreter,
2141start an interactive interpreter and have a short session like this:
2142
2143\begin{verbatim}
2144>>> import distutils.sysconfig
2145>>> distutils.sysconfig.LINKFORSHARED
2146'-Xlinker -export-dynamic'
2147\end{verbatim}
2148\refstmodindex{distutils.sysconfig}
2149
2150The contents of the string presented will be the options that should
2151be used. If the string is empty, there's no need to add any
2152additional options. The \constant{LINKFORSHARED} definition
2153corresponds to the variable of the same name in Python's top-level
2154\file{Makefile}.
2155
Fred Drakeed773ef2000-09-21 21:35:22 +00002156
2157\appendix
2158\chapter{Reporting Bugs}
2159\input{reportingbugs}
2160
Guido van Rossum7a2dba21993-11-05 14:45:11 +00002161\end{document}