Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1 | \documentstyle[twoside,11pt,myformat]{report} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 3 | % XXX PM Modulator |
| 4 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 5 | \title{Extending and Embedding the Python Interpreter} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 7 | \input{boilerplate} |
Guido van Rossum | 83eb962 | 1993-11-23 16:28:45 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 9 | % Tell \index to actually write the .idx file |
| 10 | \makeindex |
| 11 | |
| 12 | \begin{document} |
| 13 | |
| 14 | \pagenumbering{roman} |
| 15 | |
| 16 | \maketitle |
| 17 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 18 | \input{copyright} |
| 19 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 20 | \begin{abstract} |
| 21 | |
| 22 | \noindent |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 23 | Python is an interpreted, object-oriented programming language. This |
| 24 | document describes how to write modules in C or \Cpp{} to extend the |
| 25 | Python interpreter with new modules. Those modules can define new |
| 26 | functions but also new object types and their methods. The document |
| 27 | also describes how to embed the Python interpreter in another |
| 28 | application, for use as an extension language. Finally, it shows how |
| 29 | to compile and link extension modules so that they can be loaded |
| 30 | dynamically (at run time) into the interpreter, if the underlying |
| 31 | operating system supports this feature. |
| 32 | |
| 33 | This document assumes basic knowledge about Python. For an informal |
| 34 | introduction to the language, see the Python Tutorial. The Python |
| 35 | Reference Manual gives a more formal definition of the language. The |
| 36 | Python Library Reference documents the existing object types, |
| 37 | functions and modules (both built-in and written in Python) that give |
| 38 | the language its wide application range. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 39 | |
| 40 | \end{abstract} |
| 41 | |
| 42 | \pagebreak |
| 43 | |
| 44 | { |
| 45 | \parskip = 0mm |
| 46 | \tableofcontents |
| 47 | } |
| 48 | |
| 49 | \pagebreak |
| 50 | |
| 51 | \pagenumbering{arabic} |
| 52 | |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 53 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 54 | \chapter{Extending Python with C or \Cpp{} code} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 55 | |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 56 | |
| 57 | \section{Introduction} |
| 58 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 59 | It is quite easy to add new built-in modules to Python, if you know |
| 60 | how to program in C. Such \dfn{extension modules} can do two things |
| 61 | that can't be done directly in Python: they can implement new built-in |
| 62 | object types, and they can call C library functions and system calls. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 63 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 64 | To support extensions, the Python API (Application Programmers |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 65 | Interface) defines a set of functions, macros and variables that |
| 66 | provide access to most aspects of the Python run-time system. The |
| 67 | Python API is incorporated in a C source file by including the header |
| 68 | \code{"Python.h"}. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 69 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 70 | The compilation of an extension module depends on its intended use as |
| 71 | well as on your system setup; details are given in a later section. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 72 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 73 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 74 | \section{A Simple Example} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 75 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 76 | Let's create an extension module called \samp{spam} (the favorite food |
| 77 | of Monty Python fans...) and let's say we want to create a Python |
| 78 | interface to the C library function \code{system()}.\footnote{An |
| 79 | interface for this function already exists in the standard module |
| 80 | \code{os} --- it was chosen as a simple and straightfoward example.} |
| 81 | This function takes a null-terminated character string as argument and |
| 82 | returns an integer. We want this function to be callable from Python |
| 83 | as follows: |
| 84 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 85 | \bcode\begin{verbatim} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 86 | >>> import spam |
| 87 | >>> status = spam.system("ls -l") |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 88 | \end{verbatim}\ecode |
| 89 | % |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 90 | Begin by creating a file \samp{spammodule.c}. (In general, if a |
| 91 | module is called \samp{spam}, the C file containing its implementation |
| 92 | is called \file{spammodule.c}; if the module name is very long, like |
| 93 | \samp{spammify}, the module name can be just \file{spammify.c}.) |
| 94 | |
| 95 | The first line of our file can be: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 96 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 97 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 98 | #include "Python.h" |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 99 | \end{verbatim}\ecode |
| 100 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 101 | which pulls in the Python API (you can add a comment describing the |
| 102 | purpose of the module and a copyright notice if you like). |
| 103 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 104 | All user-visible symbols defined by \code{"Python.h"} have a prefix of |
| 105 | \samp{Py} or \samp{PY}, except those defined in standard header files. |
| 106 | For convenience, and since they are used extensively by the Python |
| 107 | interpreter, \code{"Python.h"} includes a few standard header files: |
| 108 | \code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and |
| 109 | \code{<stdlib.h>}. If the latter header file does not exist on your |
| 110 | system, it declares the functions \code{malloc()}, \code{free()} and |
| 111 | \code{realloc()} directly. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 112 | |
| 113 | The next thing we add to our module file is the C function that will |
| 114 | be called when the Python expression \samp{spam.system(\var{string})} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 115 | is evaluated (we'll see shortly how it ends up being called): |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 116 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 117 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 118 | static PyObject * |
| 119 | spam_system(self, args) |
| 120 | PyObject *self; |
| 121 | PyObject *args; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 122 | { |
| 123 | char *command; |
| 124 | int sts; |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 125 | if (!PyArg_ParseTuple(args, "s", &command)) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 126 | return NULL; |
| 127 | sts = system(command); |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 128 | return Py_BuildValue("i", sts); |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 129 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 130 | \end{verbatim}\ecode |
| 131 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 132 | There is a straightforward translation from the argument list in |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 133 | Python (e.g.\ the single expression \code{"ls -l"}) to the arguments |
| 134 | passed to the C function. The C function always has two arguments, |
| 135 | conventionally named \var{self} and \var{args}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 136 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 137 | The \var{self} argument is only used when the C function implements a |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 138 | builtin method. This will be discussed later. In the example, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 139 | \var{self} will always be a \code{NULL} pointer, since we are defining |
| 140 | a function, not a method. (This is done so that the interpreter |
| 141 | doesn't have to understand two different types of C functions.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 142 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 143 | The \var{args} argument will be a pointer to a Python tuple object |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 144 | containing the arguments. Each item of the tuple corresponds to an |
| 145 | argument in the call's argument list. The arguments are Python |
| 146 | objects -- in order to do anything with them in our C function we have |
| 147 | to convert them to C values. The function \code{PyArg_ParseTuple()} |
| 148 | in the Python API checks the argument types and converts them to C |
| 149 | values. It uses a template string to determine the required types of |
| 150 | the arguments as well as the types of the C variables into which to |
| 151 | store the converted values. More about this later. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 152 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 153 | \code{PyArg_ParseTuple()} returns true (nonzero) if all arguments have |
| 154 | the right type and its components have been stored in the variables |
| 155 | whose addresses are passed. It returns false (zero) if an invalid |
| 156 | argument list was passed. In the latter case it also raises an |
| 157 | appropriate exception by so the calling function can return |
| 158 | \code{NULL} immediately (as we saw in the example). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 159 | |
| 160 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 161 | \section{Intermezzo: Errors and Exceptions} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 162 | |
| 163 | An important convention throughout the Python interpreter is the |
| 164 | following: when a function fails, it should set an exception condition |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 165 | and return an error value (usually a \code{NULL} pointer). Exceptions |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 166 | are stored in a static global variable inside the interpreter; if this |
| 167 | variable is \code{NULL} no exception has occurred. A second global |
| 168 | variable stores the ``associated value'' of the exception (the second |
| 169 | argument to \code{raise}). A third variable contains the stack |
| 170 | traceback in case the error originated in Python code. These three |
| 171 | variables are the C equivalents of the Python variables |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 172 | \code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 173 | (see the section on module \code{sys} in the Library Reference |
| 174 | Manual). It is important to know about them to understand how errors |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 175 | are passed around. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 176 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 177 | The Python API defines a number of functions to set various types of |
| 178 | exceptions. |
| 179 | |
| 180 | The most common one is \code{PyErr_SetString()}. Its arguments are an |
| 181 | exception object and a C string. The exception object is usually a |
| 182 | predefined object like \code{PyExc_ZeroDivisionError}. The C string |
| 183 | indicates the cause of the error and is converted to a Python string |
| 184 | object and stored as the ``associated value'' of the exception. |
| 185 | |
| 186 | Another useful function is \code{PyErr_SetFromErrno()}, which only |
| 187 | takes an exception argument and constructs the associated value by |
| 188 | inspection of the (\UNIX{}) global variable \code{errno}. The most |
| 189 | general function is \code{PyErr_SetObject()}, which takes two object |
| 190 | arguments, the exception and its associated value. You don't need to |
| 191 | \code{Py_INCREF()} the objects passed to any of these functions. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 192 | |
| 193 | You can test non-destructively whether an exception has been set with |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 194 | \code{PyErr_Occurred()}. This returns the current exception object, |
| 195 | or \code{NULL} if no exception has occurred. You normally don't need |
| 196 | to call \code{PyErr_Occurred()} to see whether an error occurred in a |
| 197 | function call, since you should be able to tell from the return value. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 198 | |
Guido van Rossum | d16ddb6 | 1996-12-13 02:38:17 +0000 | [diff] [blame] | 199 | When a function \var{f} that calls another function \var{g} detects |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 200 | that the latter fails, \var{f} should itself return an error value |
| 201 | (e.g. \code{NULL} or \code{-1}). It should \emph{not} call one of the |
| 202 | \code{PyErr_*()} functions --- one has already been called by \var{g}. |
| 203 | \var{f}'s caller is then supposed to also return an error indication |
| 204 | to \emph{its} caller, again \emph{without} calling \code{PyErr_*()}, |
| 205 | and so on --- the most detailed cause of the error was already |
| 206 | reported by the function that first detected it. Once the error |
| 207 | reaches the Python interpreter's main loop, this aborts the currently |
| 208 | executing Python code and tries to find an exception handler specified |
| 209 | by the Python programmer. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 210 | |
| 211 | (There are situations where a module can actually give a more detailed |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 212 | error message by calling another \code{PyErr_*()} function, and in |
| 213 | such cases it is fine to do so. As a general rule, however, this is |
| 214 | not necessary, and can cause information about the cause of the error |
| 215 | to be lost: most operations can fail for a variety of reasons.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 216 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 217 | To ignore an exception set by a function call that failed, the exception |
| 218 | condition must be cleared explicitly by calling \code{PyErr_Clear()}. |
| 219 | The only time C code should call \code{PyErr_Clear()} is if it doesn't |
| 220 | want to pass the error on to the interpreter but wants to handle it |
| 221 | completely by itself (e.g. by trying something else or pretending |
| 222 | nothing happened). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 223 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 224 | Note that a failing \code{malloc()} call must be turned into an |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 225 | exception --- the direct caller of \code{malloc()} (or |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 226 | \code{realloc()}) must call \code{PyErr_NoMemory()} and return a |
| 227 | failure indicator itself. All the object-creating functions |
| 228 | (\code{PyInt_FromLong()} etc.) already do this, so only if you call |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 229 | \code{malloc()} directly this note is of importance. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 230 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 231 | Also note that, with the important exception of |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 232 | \code{PyArg_ParseTuple()} and friends, functions that return an |
| 233 | integer status usually return a positive value or zero for success and |
| 234 | \code{-1} for failure, like \UNIX{} system calls. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 235 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 236 | Finally, be careful to clean up garbage (by making \code{Py_XDECREF()} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 237 | or \code{Py_DECREF()} calls for objects you have already created) when |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 238 | you return an error indicator! |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 239 | |
| 240 | The choice of which exception to raise is entirely yours. There are |
| 241 | predeclared C objects corresponding to all built-in Python exceptions, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 242 | e.g. \code{PyExc_ZeroDevisionError} which you can use directly. Of |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 243 | course, you should choose exceptions wisely --- don't use |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 244 | \code{PyExc_TypeError} to mean that a file couldn't be opened (that |
| 245 | should probably be \code{PyExc_IOError}). If something's wrong with |
| 246 | the argument list, the \code{PyArg_ParseTuple()} function usually |
| 247 | raises \code{PyExc_TypeError}. If you have an argument whose value |
| 248 | which must be in a particular range or must satisfy other conditions, |
| 249 | \code{PyExc_ValueError} is appropriate. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 250 | |
| 251 | You can also define a new exception that is unique to your module. |
| 252 | For this, you usually declare a static object variable at the |
| 253 | beginning of your file, e.g. |
| 254 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 255 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 256 | static PyObject *SpamError; |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 257 | \end{verbatim}\ecode |
| 258 | % |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 259 | and initialize it in your module's initialization function |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 260 | (\code{initspam()}) with a string object, e.g. (leaving out the error |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 261 | checking for now): |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 262 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 263 | \bcode\begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 264 | void |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 265 | initspam() |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 266 | { |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 267 | PyObject *m, *d; |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 268 | m = Py_InitModule("spam", SpamMethods); |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 269 | d = PyModule_GetDict(m); |
| 270 | SpamError = PyString_FromString("spam.error"); |
| 271 | PyDict_SetItemString(d, "error", SpamError); |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 272 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 273 | \end{verbatim}\ecode |
| 274 | % |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 275 | Note that the Python name for the exception object is |
| 276 | \code{spam.error}. It is conventional for module and exception names |
| 277 | to be spelled in lower case. It is also conventional that the |
| 278 | \emph{value} of the exception object is the same as its name, e.g.\ |
| 279 | the string \code{"spam.error"}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 280 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 281 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 282 | \section{Back to the Example} |
| 283 | |
| 284 | Going back to our example function, you should now be able to |
| 285 | understand this statement: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 286 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 287 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 288 | if (!PyArg_ParseTuple(args, "s", &command)) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 289 | return NULL; |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 290 | \end{verbatim}\ecode |
| 291 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 292 | It returns \code{NULL} (the error indicator for functions returning |
| 293 | object pointers) if an error is detected in the argument list, relying |
| 294 | on the exception set by \code{PyArg_ParseTuple()}. Otherwise the |
| 295 | string value of the argument has been copied to the local variable |
| 296 | \code{command}. This is a pointer assignment and you are not supposed |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 297 | to modify the string to which it points (so in Standard C, the variable |
| 298 | \code{command} should properly be declared as \samp{const char |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 299 | *command}). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 300 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 301 | The next statement is a call to the \UNIX{} function \code{system()}, |
| 302 | passing it the string we just got from \code{PyArg_ParseTuple()}: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 303 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 304 | \bcode\begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 305 | sts = system(command); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 306 | \end{verbatim}\ecode |
| 307 | % |
Guido van Rossum | d16ddb6 | 1996-12-13 02:38:17 +0000 | [diff] [blame] | 308 | Our \code{spam.system()} function must return the value of \code{sts} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 309 | as a Python object. This is done using the function |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 310 | \code{Py_BuildValue()}, which is something like the inverse of |
| 311 | \code{PyArg_ParseTuple()}: it takes a format string and an arbitrary |
| 312 | number of C values, and returns a new Python object. More info on |
| 313 | \code{Py_BuildValue()} is given later. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 314 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 315 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 316 | return Py_BuildValue("i", sts); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 317 | \end{verbatim}\ecode |
| 318 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 319 | In this case, it will return an integer object. (Yes, even integers |
| 320 | are objects on the heap in Python!) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 321 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 322 | If you have a C function that returns no useful argument (a function |
| 323 | returning \code{void}), the corresponding Python function must return |
| 324 | \code{None}. You need this idiom to do so: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 325 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 326 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 327 | Py_INCREF(Py_None); |
| 328 | return Py_None; |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 329 | \end{verbatim}\ecode |
| 330 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 331 | \code{Py_None} is the C name for the special Python object |
| 332 | \code{None}. It is a genuine Python object (not a \code{NULL} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 333 | pointer, which means ``error'' in most contexts, as we have seen). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 334 | |
| 335 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 336 | \section{The Module's Method Table and Initialization Function} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 337 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 338 | I promised to show how \code{spam_system()} is called from Python |
| 339 | programs. First, we need to list its name and address in a ``method |
| 340 | table'': |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 341 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 342 | \bcode\begin{verbatim} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 343 | static PyMethodDef SpamMethods[] = { |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 344 | ... |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 345 | {"system", spam_system, 1}, |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 346 | ... |
| 347 | {NULL, NULL} /* Sentinel */ |
| 348 | }; |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 349 | \end{verbatim}\ecode |
| 350 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 351 | Note the third entry (\samp{1}). This is a flag telling the |
| 352 | interpreter the calling convention to be used for the C function. It |
| 353 | should normally always be \samp{1}; a value of \samp{0} means that an |
| 354 | obsolete variant of \code{PyArg_ParseTuple()} is used. |
| 355 | |
| 356 | The method table must be passed to the interpreter in the module's |
| 357 | initialization function (which should be the only non-\code{static} |
| 358 | item defined in the module file): |
| 359 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 360 | \bcode\begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 361 | void |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 362 | initspam() |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 363 | { |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 364 | (void) Py_InitModule("spam", SpamMethods); |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 365 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 366 | \end{verbatim}\ecode |
| 367 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 368 | When the Python program imports module \code{spam} for the first time, |
| 369 | \code{initspam()} is called. It calls \code{Py_InitModule()}, which |
| 370 | creates a ``module object'' (which is inserted in the dictionary |
| 371 | \code{sys.modules} under the key \code{"spam"}), and inserts built-in |
| 372 | function objects into the newly created module based upon the table |
| 373 | (an array of \code{PyMethodDef} structures) that was passed as its |
| 374 | second argument. \code{Py_InitModule()} returns a pointer to the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 375 | module object that it creates (which is unused here). It aborts with |
| 376 | a fatal error if the module could not be initialized satisfactorily, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 377 | so the caller doesn't need to check for errors. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 378 | |
| 379 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 380 | \section{Compilation and Linkage} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 381 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 382 | There are two more things to do before you can use your new extension: |
| 383 | compiling and linking it with the Python system. If you use dynamic |
| 384 | loading, the details depend on the style of dynamic loading your |
| 385 | system uses; see the chapter on Dynamic Loading for more info about |
| 386 | this. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 387 | |
| 388 | If you can't use dynamic loading, or if you want to make your module a |
| 389 | permanent part of the Python interpreter, you will have to change the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 390 | configuration setup and rebuild the interpreter. Luckily, this is |
| 391 | very simple: just place your file (\file{spammodule.c} for example) in |
| 392 | the \file{Modules} directory, add a line to the file |
| 393 | \file{Modules/Setup} describing your file: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 394 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 395 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 396 | spam spammodule.o |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 397 | \end{verbatim}\ecode |
| 398 | % |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 399 | and rebuild the interpreter by running \code{make} in the toplevel |
| 400 | directory. You can also run \code{make} in the \file{Modules} |
| 401 | subdirectory, but then you must first rebuilt the \file{Makefile} |
| 402 | there by running \code{make Makefile}. (This is necessary each time |
| 403 | you change the \file{Setup} file.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 404 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 405 | If your module requires additional libraries to link with, these can |
| 406 | be listed on the line in the \file{Setup} file as well, for instance: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 407 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 408 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 409 | spam spammodule.o -lX11 |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 410 | \end{verbatim}\ecode |
| 411 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 412 | \section{Calling Python Functions From C} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 413 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 414 | So far we have concentrated on making C functions callable from |
| 415 | Python. The reverse is also useful: calling Python functions from C. |
| 416 | This is especially the case for libraries that support so-called |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 417 | ``callback'' functions. If a C interface makes use of callbacks, the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 418 | equivalent Python often needs to provide a callback mechanism to the |
| 419 | Python programmer; the implementation will require calling the Python |
| 420 | callback functions from a C callback. Other uses are also imaginable. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 421 | |
| 422 | Fortunately, the Python interpreter is easily called recursively, and |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 423 | there is a standard interface to call a Python function. (I won't |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 424 | dwell on how to call the Python parser with a particular string as |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 425 | input --- if you're interested, have a look at the implementation of |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 426 | the \samp{-c} command line option in \file{Python/pythonmain.c}.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 427 | |
| 428 | Calling a Python function is easy. First, the Python program must |
| 429 | somehow pass you the Python function object. You should provide a |
| 430 | function (or some other interface) to do this. When this function is |
| 431 | called, save a pointer to the Python function object (be careful to |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 432 | \code{Py_INCREF()} it!) in a global variable --- or whereever you see fit. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 433 | For example, the following function might be part of a module |
| 434 | definition: |
| 435 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 436 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 437 | static PyObject *my_callback = NULL; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 438 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 439 | static PyObject * |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 440 | my_set_callback(dummy, arg) |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 441 | PyObject *dummy, *arg; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 442 | { |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 443 | Py_XDECREF(my_callback); /* Dispose of previous callback */ |
| 444 | Py_XINCREF(arg); /* Add a reference to new callback */ |
| 445 | my_callback = arg; /* Remember new callback */ |
| 446 | /* Boilerplate to return "None" */ |
| 447 | Py_INCREF(Py_None); |
| 448 | return Py_None; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 449 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 450 | \end{verbatim}\ecode |
| 451 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 452 | The macros \code{Py_XINCREF()} and \code{Py_XDECREF()} increment/decrement |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 453 | the reference count of an object and are safe in the presence of |
| 454 | \code{NULL} pointers. More info on them in the section on Reference |
| 455 | Counts below. |
| 456 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 457 | Later, when it is time to call the function, you call the C function |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 458 | \code{PyEval_CallObject()}. This function has two arguments, both |
| 459 | pointers to arbitrary Python objects: the Python function, and the |
| 460 | argument list. The argument list must always be a tuple object, whose |
| 461 | length is the number of arguments. To call the Python function with |
| 462 | no arguments, pass an empty tuple; to call it with one argument, pass |
| 463 | a singleton tuple. \code{Py_BuildValue()} returns a tuple when its |
| 464 | format string consists of zero or more format codes between |
| 465 | parentheses. For example: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 466 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 467 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 468 | int arg; |
| 469 | PyObject *arglist; |
| 470 | PyObject *result; |
| 471 | ... |
| 472 | arg = 123; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 473 | ... |
| 474 | /* Time to call the callback */ |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 475 | arglist = Py_BuildValue("(i)", arg); |
| 476 | result = PyEval_CallObject(my_callback, arglist); |
| 477 | Py_DECREF(arglist); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 478 | \end{verbatim}\ecode |
| 479 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 480 | \code{PyEval_CallObject()} returns a Python object pointer: this is |
| 481 | the return value of the Python function. \code{PyEval_CallObject()} is |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 482 | ``reference-count-neutral'' with respect to its arguments. In the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 483 | example a new tuple was created to serve as the argument list, which |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 484 | is \code{Py_DECREF()}-ed immediately after the call. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 485 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 486 | The return value of \code{PyEval_CallObject()} is ``new'': either it |
| 487 | is a brand new object, or it is an existing object whose reference |
| 488 | count has been incremented. So, unless you want to save it in a |
| 489 | global variable, you should somehow \code{Py_DECREF()} the result, |
| 490 | even (especially!) if you are not interested in its value. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 491 | |
| 492 | Before you do this, however, it is important to check that the return |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 493 | value isn't \code{NULL}. If it is, the Python function terminated by raising |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 494 | an exception. If the C code that called \code{PyEval_CallObject()} is |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 495 | called from Python, it should now return an error indication to its |
| 496 | Python caller, so the interpreter can print a stack trace, or the |
| 497 | calling Python code can handle the exception. If this is not possible |
| 498 | or desirable, the exception should be cleared by calling |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 499 | \code{PyErr_Clear()}. For example: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 500 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 501 | \bcode\begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 502 | if (result == NULL) |
| 503 | return NULL; /* Pass error back */ |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 504 | ...use result... |
| 505 | Py_DECREF(result); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 506 | \end{verbatim}\ecode |
| 507 | % |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 508 | Depending on the desired interface to the Python callback function, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 509 | you may also have to provide an argument list to \code{PyEval_CallObject()}. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 510 | In some cases the argument list is also provided by the Python |
| 511 | program, through the same interface that specified the callback |
| 512 | function. It can then be saved and used in the same manner as the |
| 513 | function object. In other cases, you may have to construct a new |
| 514 | tuple to pass as the argument list. The simplest way to do this is to |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 515 | call \code{Py_BuildValue()}. For example, if you want to pass an integral |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 516 | event code, you might use the following code: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 517 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 518 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 519 | PyObject *arglist; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 520 | ... |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 521 | arglist = Py_BuildValue("(l)", eventcode); |
| 522 | result = PyEval_CallObject(my_callback, arglist); |
| 523 | Py_DECREF(arglist); |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 524 | if (result == NULL) |
| 525 | return NULL; /* Pass error back */ |
| 526 | /* Here maybe use the result */ |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 527 | Py_DECREF(result); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 528 | \end{verbatim}\ecode |
| 529 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 530 | Note the placement of \code{Py_DECREF(argument)} immediately after the call, |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 531 | before the error check! Also note that strictly spoken this code is |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 532 | not complete: \code{Py_BuildValue()} may run out of memory, and this should |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 533 | be checked. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 534 | |
| 535 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 536 | \section{Format Strings for {\tt PyArg_ParseTuple()}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 537 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 538 | The \code{PyArg_ParseTuple()} function is declared as follows: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 539 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 540 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 541 | int PyArg_ParseTuple(PyObject *arg, char *format, ...); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 542 | \end{verbatim}\ecode |
| 543 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 544 | The \var{arg} argument must be a tuple object containing an argument |
| 545 | list passed from Python to a C function. The \var{format} argument |
| 546 | must be a format string, whose syntax is explained below. The |
| 547 | remaining arguments must be addresses of variables whose type is |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 548 | determined by the format string. For the conversion to succeed, the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 549 | \var{arg} object must match the format and the format must be |
| 550 | exhausted. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 551 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 552 | Note that while \code{PyArg_ParseTuple()} checks that the Python |
| 553 | arguments have the required types, it cannot check the validity of the |
| 554 | addresses of C variables passed to the call: if you make mistakes |
| 555 | there, your code will probably crash or at least overwrite random bits |
| 556 | in memory. So be careful! |
| 557 | |
| 558 | A format string consists of zero or more ``format units''. A format |
| 559 | unit describes one Python object; it is usually a single character or |
| 560 | a parenthesized sequence of format units. With a few exceptions, a |
| 561 | format unit that is not a parenthesized sequence normally corresponds |
| 562 | to a single address argument to \code{PyArg_ParseTuple()}. In the |
| 563 | following description, the quoted form is the format unit; the entry |
| 564 | in (round) parentheses is the Python object type that matches the |
| 565 | format unit; and the entry in [square] brackets is the type of the C |
| 566 | variable(s) whose address should be passed. (Use the \samp{\&} |
| 567 | operator to pass a variable's address.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 568 | |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 569 | \begin{description} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 570 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 571 | \item[\samp{s} (string) [char *]] |
| 572 | Convert a Python string to a C pointer to a character string. You |
| 573 | must not provide storage for the string itself; a pointer to an |
| 574 | existing string is stored into the character pointer variable whose |
| 575 | address you pass. The C string is null-terminated. The Python string |
| 576 | must not contain embedded null bytes; if it does, a \code{TypeError} |
| 577 | exception is raised. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 578 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 579 | \item[\samp{s\#} (string) {[char *, int]}] |
| 580 | This variant on \code{'s'} stores into two C variables, the first one |
| 581 | a pointer to a character string, the second one its length. In this |
| 582 | case the Python string may contain embedded null bytes. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 583 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 584 | \item[\samp{z} (string or \code{None}) {[char *]}] |
| 585 | Like \samp{s}, but the Python object may also be \code{None}, in which |
| 586 | case the C pointer is set to \code{NULL}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 587 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 588 | \item[\samp{z\#} (string or \code{None}) {[char *, int]}] |
| 589 | This is to \code{'s\#'} as \code{'z'} is to \code{'s'}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 590 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 591 | \item[\samp{b} (integer) {[char]}] |
| 592 | Convert a Python integer to a tiny int, stored in a C \code{char}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 593 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 594 | \item[\samp{h} (integer) {[short int]}] |
| 595 | Convert a Python integer to a C \code{short int}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 596 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 597 | \item[\samp{i} (integer) {[int]}] |
| 598 | Convert a Python integer to a plain C \code{int}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 599 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 600 | \item[\samp{l} (integer) {[long int]}] |
| 601 | Convert a Python integer to a C \code{long int}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 602 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 603 | \item[\samp{c} (string of length 1) {[char]}] |
| 604 | Convert a Python character, represented as a string of length 1, to a |
| 605 | C \code{char}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 606 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 607 | \item[\samp{f} (float) {[float]}] |
| 608 | Convert a Python floating point number to a C \code{float}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 609 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 610 | \item[\samp{d} (float) {[double]}] |
| 611 | Convert a Python floating point number to a C \code{double}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 612 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 613 | \item[\samp{O} (object) {[PyObject *]}] |
| 614 | Store a Python object (without any conversion) in a C object pointer. |
| 615 | The C program thus receives the actual object that was passed. The |
| 616 | object's reference count is not increased. The pointer stored is not |
| 617 | \code{NULL}. |
| 618 | |
| 619 | \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}] |
| 620 | Store a Python object in a C object pointer. This is similar to |
| 621 | \samp{O}, but takes two C arguments: the first is the address of a |
| 622 | Python type object, the second is the address of the C variable (of |
| 623 | type \code{PyObject *}) into which the object pointer is stored. |
| 624 | If the Python object does not have the required type, a |
| 625 | \code{TypeError} exception is raised. |
| 626 | |
| 627 | \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}] |
| 628 | Convert a Python object to a C variable through a \var{converter} |
| 629 | function. This takes two arguments: the first is a function, the |
| 630 | second is the address of a C variable (of arbitrary type), converted |
| 631 | to \code{void *}. The \var{converter} function in turn is called as |
| 632 | follows: |
| 633 | |
| 634 | \code{\var{status} = \var{converter}(\var{object}, \var{address});} |
| 635 | |
| 636 | where \var{object} is the Python object to be converted and |
| 637 | \var{address} is the \code{void *} argument that was passed to |
| 638 | \code{PyArg_ConvertTuple()}. The returned \var{status} should be |
| 639 | \code{1} for a successful conversion and \code{0} if the conversion |
| 640 | has failed. When the conversion fails, the \var{converter} function |
| 641 | should raise an exception. |
| 642 | |
| 643 | \item[\samp{S} (string) {[PyStringObject *]}] |
| 644 | Like \samp{O} but raises a \code{TypeError} exception that the object |
| 645 | is a string object. The C variable may also be declared as |
| 646 | \code{PyObject *}. |
| 647 | |
| 648 | \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}] |
| 649 | The object must be a Python tuple whose length is the number of format |
| 650 | units in \var{items}. The C arguments must correspond to the |
| 651 | individual format units in \var{items}. Format units for tuples may |
| 652 | be nested. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 653 | |
| 654 | \end{description} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 655 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 656 | It is possible to pass Python long integers where integers are |
| 657 | requested; however no proper range checking is done -- the most |
| 658 | significant bits are silently truncated when the receiving field is |
| 659 | too small to receive the value (actually, the semantics are inherited |
| 660 | from downcasts in C --- your milage may vary). |
| 661 | |
| 662 | A few other characters have a meaning in a format string. These may |
| 663 | not occur inside nested parentheses. They are: |
| 664 | |
| 665 | \begin{description} |
| 666 | |
| 667 | \item[\samp{|}] |
| 668 | Indicates that the remaining arguments in the Python argument list are |
| 669 | optional. The C variables corresponding to optional arguments should |
| 670 | be initialized to their default value --- when an optional argument is |
| 671 | not specified, the \code{PyArg_ParseTuple} does not touch the contents |
| 672 | of the corresponding C variable(s). |
| 673 | |
| 674 | \item[\samp{:}] |
| 675 | The list of format units ends here; the string after the colon is used |
| 676 | as the function name in error messages (the ``associated value'' of |
| 677 | the exceptions that \code{PyArg_ParseTuple} raises). |
| 678 | |
| 679 | \item[\samp{;}] |
| 680 | The list of format units ends here; the string after the colon is used |
| 681 | as the error message \emph{instead} of the default error message. |
| 682 | Clearly, \samp{:} and \samp{;} mutually exclude each other. |
| 683 | |
| 684 | \end{description} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 685 | |
| 686 | Some example calls: |
| 687 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 688 | \bcode\begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 689 | int ok; |
| 690 | int i, j; |
| 691 | long k, l; |
| 692 | char *s; |
| 693 | int size; |
| 694 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 695 | ok = PyArg_ParseTuple(args, ""); /* No arguments */ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 696 | /* Python call: f() */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 697 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 698 | ok = PyArg_ParseTuple(args, "s", &s); /* A string */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 699 | /* Possible Python call: f('whoops!') */ |
| 700 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 701 | ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 702 | /* Possible Python call: f(1, 2, 'three') */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 703 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 704 | ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 705 | /* A pair of ints and a string, whose size is also returned */ |
Guido van Rossum | 7e924dd | 1997-02-10 16:51:52 +0000 | [diff] [blame] | 706 | /* Possible Python call: f((1, 2), 'three') */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 707 | |
| 708 | { |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 709 | char *file; |
| 710 | char *mode = "r"; |
| 711 | int bufsize = 0; |
| 712 | ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); |
| 713 | /* A string, and optionally another string and an integer */ |
| 714 | /* Possible Python calls: |
| 715 | f('spam') |
| 716 | f('spam', 'w') |
| 717 | f('spam', 'wb', 100000) */ |
| 718 | } |
| 719 | |
| 720 | { |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 721 | int left, top, right, bottom, h, v; |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 722 | ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 723 | &left, &top, &right, &bottom, &h, &v); |
| 724 | /* A rectangle and a point */ |
| 725 | /* Possible Python call: |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 726 | f(((0, 0), (400, 300)), (10, 10)) */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 727 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 728 | \end{verbatim}\ecode |
| 729 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 730 | \section{The {\tt Py_BuildValue()} Function} |
| 731 | |
| 732 | This function is the counterpart to \code{PyArg_ParseTuple()}. It is |
| 733 | declared as follows: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 734 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 735 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 736 | PyObject *Py_BuildValue(char *format, ...); |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 737 | \end{verbatim}\ecode |
| 738 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 739 | It recognizes a set of format units similar to the ones recognized by |
| 740 | \code{PyArg_ParseTuple()}, but the arguments (which are input to the |
| 741 | function, not output) must not be pointers, just values. It returns a |
| 742 | new Python object, suitable for returning from a C function called |
| 743 | from Python. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 744 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 745 | One difference with \code{PyArg_ParseTuple()}: while the latter |
| 746 | requires its first argument to be a tuple (since Python argument lists |
| 747 | are always represented as tuples internally), \code{BuildValue()} does |
| 748 | not always build a tuple. It builds a tuple only if its format string |
| 749 | contains two or more format units. If the format string is empty, it |
| 750 | returns \code{None}; if it contains exactly one format unit, it |
| 751 | returns whatever object is described by that format unit. To force it |
| 752 | to return a tuple of size 0 or one, parenthesize the format string. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 753 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 754 | In the following description, the quoted form is the format unit; the |
| 755 | entry in (round) parentheses is the Python object type that the format |
| 756 | unit will return; and the entry in [square] brackets is the type of |
| 757 | the C value(s) to be passed. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 758 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 759 | The characters space, tab, colon and comma are ignored in format |
| 760 | strings (but not within format units such as \samp{s\#}). This can be |
| 761 | used to make long format strings a tad more readable. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 762 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 763 | \begin{description} |
| 764 | |
| 765 | \item[\samp{s} (string) {[char *]}] |
| 766 | Convert a null-terminated C string to a Python object. If the C |
| 767 | string pointer is \code{NULL}, \code{None} is returned. |
| 768 | |
| 769 | \item[\samp{s\#} (string) {[char *, int]}] |
| 770 | Convert a C string and its length to a Python object. If the C string |
| 771 | pointer is \code{NULL}, the length is ignored and \code{None} is |
| 772 | returned. |
| 773 | |
| 774 | \item[\samp{z} (string or \code{None}) {[char *]}] |
| 775 | Same as \samp{s}. |
| 776 | |
| 777 | \item[\samp{z\#} (string or \code{None}) {[char *, int]}] |
| 778 | Same as \samp{s\#}. |
| 779 | |
| 780 | \item[\samp{i} (integer) {[int]}] |
| 781 | Convert a plain C \code{int} to a Python integer object. |
| 782 | |
| 783 | \item[\samp{b} (integer) {[char]}] |
| 784 | Same as \samp{i}. |
| 785 | |
| 786 | \item[\samp{h} (integer) {[short int]}] |
| 787 | Same as \samp{i}. |
| 788 | |
| 789 | \item[\samp{l} (integer) {[long int]}] |
| 790 | Convert a C \code{long int} to a Python integer object. |
| 791 | |
| 792 | \item[\samp{c} (string of length 1) {[char]}] |
| 793 | Convert a C \code{int} representing a character to a Python string of |
| 794 | length 1. |
| 795 | |
| 796 | \item[\samp{d} (float) {[double]}] |
| 797 | Convert a C \code{double} to a Python floating point number. |
| 798 | |
| 799 | \item[\samp{f} (float) {[float]}] |
| 800 | Same as \samp{d}. |
| 801 | |
| 802 | \item[\samp{O} (object) {[PyObject *]}] |
| 803 | Pass a Python object untouched (except for its reference count, which |
| 804 | is incremented by one). If the object passed in is a \code{NULL} |
| 805 | pointer, it is assumed that this was caused because the call producing |
| 806 | the argument found an error and set an exception. Therefore, |
| 807 | \code{Py_BuildValue()} will return \code{NULL} but won't raise an |
| 808 | exception. If no exception has been raised yet, |
| 809 | \code{PyExc_SystemError} is set. |
| 810 | |
| 811 | \item[\samp{S} (object) {[PyObject *]}] |
| 812 | Same as \samp{O}. |
| 813 | |
| 814 | \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}] |
| 815 | Convert \var{anything} to a Python object through a \var{converter} |
| 816 | function. The function is called with \var{anything} (which should be |
| 817 | compatible with \code{void *}) as its argument and should return a |
| 818 | ``new'' Python object, or \code{NULL} if an error occurred. |
| 819 | |
| 820 | \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}] |
| 821 | Convert a sequence of C values to a Python tuple with the same number |
| 822 | of items. |
| 823 | |
| 824 | \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}] |
| 825 | Convert a sequence of C values to a Python list with the same number |
| 826 | of items. |
| 827 | |
| 828 | \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}] |
| 829 | Convert a sequence of C values to a Python dictionary. Each pair of |
| 830 | consecutive C values adds one item to the dictionary, serving as key |
| 831 | and value, respectively. |
| 832 | |
| 833 | \end{description} |
| 834 | |
| 835 | If there is an error in the format string, the |
| 836 | \code{PyExc_SystemError} exception is raised and \code{NULL} returned. |
| 837 | |
| 838 | Examples (to the left the call, to the right the resulting Python value): |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 839 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 840 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 841 | Py_BuildValue("") None |
| 842 | Py_BuildValue("i", 123) 123 |
Guido van Rossum | f23e0fe | 1995-03-18 11:04:29 +0000 | [diff] [blame] | 843 | Py_BuildValue("iii", 123, 456, 789) (123, 456, 789) |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 844 | Py_BuildValue("s", "hello") 'hello' |
| 845 | Py_BuildValue("ss", "hello", "world") ('hello', 'world') |
| 846 | Py_BuildValue("s#", "hello", 4) 'hell' |
| 847 | Py_BuildValue("()") () |
| 848 | Py_BuildValue("(i)", 123) (123,) |
| 849 | Py_BuildValue("(ii)", 123, 456) (123, 456) |
| 850 | Py_BuildValue("(i,i)", 123, 456) (123, 456) |
| 851 | Py_BuildValue("[i,i]", 123, 456) [123, 456] |
Guido van Rossum | f23e0fe | 1995-03-18 11:04:29 +0000 | [diff] [blame] | 852 | Py_BuildValue("{s:i,s:i}", |
| 853 | "abc", 123, "def", 456) {'abc': 123, 'def': 456} |
| 854 | Py_BuildValue("((ii)(ii)) (ii)", |
| 855 | 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6)) |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 856 | \end{verbatim}\ecode |
| 857 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 858 | \section{Reference Counts} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 859 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 860 | \subsection{Introduction} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 861 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 862 | In languages like C or \Cpp{}, the programmer is responsible for |
| 863 | dynamic allocation and deallocation of memory on the heap. In C, this |
| 864 | is done using the functions \code{malloc()} and \code{free()}. In |
| 865 | \Cpp{}, the operators \code{new} and \code{delete} are used with |
| 866 | essentially the same meaning; they are actually implemented using |
| 867 | \code{malloc()} and \code{free()}, so we'll restrict the following |
| 868 | discussion to the latter. |
| 869 | |
| 870 | Every block of memory allocated with \code{malloc()} should eventually |
| 871 | be returned to the pool of available memory by exactly one call to |
| 872 | \code{free()}. It is important to call \code{free()} at the right |
| 873 | time. If a block's address is forgotten but \code{free()} is not |
| 874 | called for it, the memory it occupies cannot be reused until the |
| 875 | program terminates. This is called a \dfn{memory leak}. On the other |
| 876 | hand, if a program calls \code{free()} for a block and then continues |
| 877 | to use the block, it creates a conflict with re-use of the block |
| 878 | through another \code{malloc()} call. This is called \dfn{using freed |
Guido van Rossum | debf2e8 | 1997-07-17 15:58:43 +0000 | [diff] [blame] | 879 | memory}. It has the same bad consequences as referencing uninitialized |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 880 | data --- core dumps, wrong results, mysterious crashes. |
| 881 | |
| 882 | Common causes of memory leaks are unusual paths through the code. For |
| 883 | instance, a function may allocate a block of memory, do some |
| 884 | calculation, and then free the block again. Now a change in the |
| 885 | requirements for the function may add a test to the calculation that |
| 886 | detects an error condition and can return prematurely from the |
| 887 | function. It's easy to forget to free the allocated memory block when |
| 888 | taking this premature exit, especially when it is added later to the |
| 889 | code. Such leaks, once introduced, often go undetected for a long |
| 890 | time: the error exit is taken only in a small fraction of all calls, |
| 891 | and most modern machines have plenty of virtual memory, so the leak |
| 892 | only becomes apparent in a long-running process that uses the leaking |
| 893 | function frequently. Therefore, it's important to prevent leaks from |
| 894 | happening by having a coding convention or strategy that minimizes |
| 895 | this kind of errors. |
| 896 | |
| 897 | Since Python makes heavy use of \code{malloc()} and \code{free()}, it |
| 898 | needs a strategy to avoid memory leaks as well as the use of freed |
| 899 | memory. The chosen method is called \dfn{reference counting}. The |
| 900 | principle is simple: every object contains a counter, which is |
| 901 | incremented when a reference to the object is stored somewhere, and |
| 902 | which is decremented when a reference to it is deleted. When the |
| 903 | counter reaches zero, the last reference to the object has been |
| 904 | deleted and the object is freed. |
| 905 | |
| 906 | An alternative strategy is called \dfn{automatic garbage collection}. |
| 907 | (Sometimes, reference counting is also referred to as a garbage |
| 908 | collection strategy, hence my use of ``automatic'' to distinguish the |
| 909 | two.) The big advantage of automatic garbage collection is that the |
| 910 | user doesn't need to call \code{free()} explicitly. (Another claimed |
| 911 | advantage is an improvement in speed or memory usage --- this is no |
| 912 | hard fact however.) The disadvantage is that for C, there is no |
| 913 | truly portable automatic garbage collector, while reference counting |
| 914 | can be implemented portably (as long as the functions \code{malloc()} |
| 915 | and \code{free()} are available --- which the C Standard guarantees). |
| 916 | Maybe some day a sufficiently portable automatic garbage collector |
| 917 | will be available for C. Until then, we'll have to live with |
| 918 | reference counts. |
| 919 | |
| 920 | \subsection{Reference Counting in Python} |
| 921 | |
| 922 | There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)}, |
| 923 | which handle the incrementing and decrementing of the reference count. |
| 924 | \code{Py_DECREF()} also frees the object when the count reaches zero. |
| 925 | For flexibility, it doesn't call \code{free()} directly --- rather, it |
| 926 | makes a call through a function pointer in the object's \dfn{type |
| 927 | object}. For this purpose (and others), every object also contains a |
| 928 | pointer to its type object. |
| 929 | |
| 930 | The big question now remains: when to use \code{Py_INCREF(x)} and |
| 931 | \code{Py_DECREF(x)}? Let's first introduce some terms. Nobody |
| 932 | ``owns'' an object; however, you can \dfn{own a reference} to an |
| 933 | object. An object's reference count is now defined as the number of |
| 934 | owned references to it. The owner of a reference is responsible for |
| 935 | calling \code{Py_DECREF()} when the reference is no longer needed. |
| 936 | Ownership of a reference can be transferred. There are three ways to |
| 937 | dispose of an owned reference: pass it on, store it, or call |
| 938 | \code{Py_DECREF()}. Forgetting to dispose of an owned reference creates |
| 939 | a memory leak. |
| 940 | |
| 941 | It is also possible to \dfn{borrow}\footnote{The metaphor of |
| 942 | ``borrowing'' a reference is not completely correct: the owner still |
| 943 | has a copy of the reference.} a reference to an object. The borrower |
| 944 | of a reference should not call \code{Py_DECREF()}. The borrower must |
| 945 | not hold on to the object longer than the owner from which it was |
| 946 | borrowed. Using a borrowed reference after the owner has disposed of |
| 947 | it risks using freed memory and should be avoided |
| 948 | completely.\footnote{Checking that the reference count is at least 1 |
| 949 | \strong{does not work} --- the reference count itself could be in |
| 950 | freed memory and may thus be reused for another object!} |
| 951 | |
| 952 | The advantage of borrowing over owning a reference is that you don't |
| 953 | need to take care of disposing of the reference on all possible paths |
| 954 | through the code --- in other words, with a borrowed reference you |
| 955 | don't run the risk of leaking when a premature exit is taken. The |
| 956 | disadvantage of borrowing over leaking is that there are some subtle |
| 957 | situations where in seemingly correct code a borrowed reference can be |
| 958 | used after the owner from which it was borrowed has in fact disposed |
| 959 | of it. |
| 960 | |
| 961 | A borrowed reference can be changed into an owned reference by calling |
| 962 | \code{Py_INCREF()}. This does not affect the status of the owner from |
| 963 | which the reference was borrowed --- it creates a new owned reference, |
| 964 | and gives full owner responsibilities (i.e., the new owner must |
| 965 | dispose of the reference properly, as well as the previous owner). |
| 966 | |
| 967 | \subsection{Ownership Rules} |
| 968 | |
| 969 | Whenever an object reference is passed into or out of a function, it |
| 970 | is part of the function's interface specification whether ownership is |
| 971 | transferred with the reference or not. |
| 972 | |
| 973 | Most functions that return a reference to an object pass on ownership |
| 974 | with the reference. In particular, all functions whose function it is |
| 975 | to create a new object, e.g.\ \code{PyInt_FromLong()} and |
| 976 | \code{Py_BuildValue()}, pass ownership to the receiver. Even if in |
| 977 | fact, in some cases, you don't receive a reference to a brand new |
| 978 | object, you still receive ownership of the reference. For instance, |
| 979 | \code{PyInt_FromLong()} maintains a cache of popular values and can |
| 980 | return a reference to a cached item. |
| 981 | |
| 982 | Many functions that extract objects from other objects also transfer |
| 983 | ownership with the reference, for instance |
| 984 | \code{PyObject_GetAttrString()}. The picture is less clear, here, |
| 985 | however, since a few common routines are exceptions: |
| 986 | \code{PyTuple_GetItem()}, \code{PyList_GetItem()} and |
| 987 | \code{PyDict_GetItem()} (and \code{PyDict_GetItemString()}) all return |
| 988 | references that you borrow from the tuple, list or dictionary. |
| 989 | |
| 990 | The function \code{PyImport_AddModule()} also returns a borrowed |
| 991 | reference, even though it may actually create the object it returns: |
| 992 | this is possible because an owned reference to the object is stored in |
| 993 | \code{sys.modules}. |
| 994 | |
| 995 | When you pass an object reference into another function, in general, |
| 996 | the function borrows the reference from you --- if it needs to store |
| 997 | it, it will use \code{Py_INCREF()} to become an independent owner. |
| 998 | There are exactly two important exceptions to this rule: |
| 999 | \code{PyTuple_SetItem()} and \code{PyList_SetItem()}. These functions |
| 1000 | take over ownership of the item passed to them --- even if they fail! |
| 1001 | (Note that \code{PyDict_SetItem()} and friends don't take over |
| 1002 | ownership --- they are ``normal''.) |
| 1003 | |
| 1004 | When a C function is called from Python, it borrows references to its |
| 1005 | arguments from the caller. The caller owns a reference to the object, |
| 1006 | so the borrowed reference's lifetime is guaranteed until the function |
| 1007 | returns. Only when such a borrowed reference must be stored or passed |
| 1008 | on, it must be turned into an owned reference by calling |
| 1009 | \code{Py_INCREF()}. |
| 1010 | |
| 1011 | The object reference returned from a C function that is called from |
| 1012 | Python must be an owned reference --- ownership is tranferred from the |
| 1013 | function to its caller. |
| 1014 | |
| 1015 | \subsection{Thin Ice} |
| 1016 | |
| 1017 | There are a few situations where seemingly harmless use of a borrowed |
| 1018 | reference can lead to problems. These all have to do with implicit |
| 1019 | invocations of the interpreter, which can cause the owner of a |
| 1020 | reference to dispose of it. |
| 1021 | |
| 1022 | The first and most important case to know about is using |
| 1023 | \code{Py_DECREF()} on an unrelated object while borrowing a reference |
| 1024 | to a list item. For instance: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1025 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1026 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1027 | bug(PyObject *list) { |
| 1028 | PyObject *item = PyList_GetItem(list, 0); |
| 1029 | PyList_SetItem(list, 1, PyInt_FromLong(0L)); |
| 1030 | PyObject_Print(item, stdout, 0); /* BUG! */ |
| 1031 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1032 | \end{verbatim}\ecode |
| 1033 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1034 | This function first borrows a reference to \code{list[0]}, then |
| 1035 | replaces \code{list[1]} with the value \code{0}, and finally prints |
| 1036 | the borrowed reference. Looks harmless, right? But it's not! |
| 1037 | |
| 1038 | Let's follow the control flow into \code{PyList_SetItem()}. The list |
| 1039 | owns references to all its items, so when item 1 is replaced, it has |
| 1040 | to dispose of the original item 1. Now let's suppose the original |
| 1041 | item 1 was an instance of a user-defined class, and let's further |
| 1042 | suppose that the class defined a \code{__del__()} method. If this |
| 1043 | class instance has a reference count of 1, disposing of it will call |
| 1044 | its \code{__del__()} method. |
| 1045 | |
| 1046 | Since it is written in Python, the \code{__del__()} method can execute |
| 1047 | arbitrary Python code. Could it perhaps do something to invalidate |
| 1048 | the reference to \code{item} in \code{bug()}? You bet! Assuming that |
| 1049 | the list passed into \code{bug()} is accessible to the |
| 1050 | \code{__del__()} method, it could execute a statement to the effect of |
| 1051 | \code{del list[0]}, and assuming this was the last reference to that |
| 1052 | object, it would free the memory associated with it, thereby |
| 1053 | invalidating \code{item}. |
| 1054 | |
| 1055 | The solution, once you know the source of the problem, is easy: |
| 1056 | temporarily increment the reference count. The correct version of the |
| 1057 | function reads: |
| 1058 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1059 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1060 | no_bug(PyObject *list) { |
| 1061 | PyObject *item = PyList_GetItem(list, 0); |
| 1062 | Py_INCREF(item); |
| 1063 | PyList_SetItem(list, 1, PyInt_FromLong(0L)); |
| 1064 | PyObject_Print(item, stdout, 0); |
| 1065 | Py_DECREF(item); |
| 1066 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1067 | \end{verbatim}\ecode |
| 1068 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1069 | This is a true story. An older version of Python contained variants |
| 1070 | of this bug and someone spent a considerable amount of time in a C |
| 1071 | debugger to figure out why his \code{__del__()} methods would fail... |
| 1072 | |
| 1073 | The second case of problems with a borrowed reference is a variant |
| 1074 | involving threads. Normally, multiple threads in the Python |
| 1075 | interpreter can't get in each other's way, because there is a global |
| 1076 | lock protecting Python's entire object space. However, it is possible |
| 1077 | to temporarily release this lock using the macro |
| 1078 | \code{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using |
| 1079 | \code{Py_END_ALLOW_THREADS}. This is common around blocking I/O |
| 1080 | calls, to let other threads use the CPU while waiting for the I/O to |
| 1081 | complete. Obviously, the following function has the same problem as |
| 1082 | the previous one: |
| 1083 | |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1084 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1085 | bug(PyObject *list) { |
| 1086 | PyObject *item = PyList_GetItem(list, 0); |
| 1087 | Py_BEGIN_ALLOW_THREADS |
| 1088 | ...some blocking I/O call... |
| 1089 | Py_END_ALLOW_THREADS |
| 1090 | PyObject_Print(item, stdout, 0); /* BUG! */ |
| 1091 | } |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1092 | \end{verbatim}\ecode |
| 1093 | % |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1094 | \subsection{NULL Pointers} |
| 1095 | |
| 1096 | In general, functions that take object references as arguments don't |
| 1097 | expect you to pass them \code{NULL} pointers, and will dump core (or |
| 1098 | cause later core dumps) if you do so. Functions that return object |
| 1099 | references generally return \code{NULL} only to indicate that an |
| 1100 | exception occurred. The reason for not testing for \code{NULL} |
| 1101 | arguments is that functions often pass the objects they receive on to |
| 1102 | other function --- if each function were to test for \code{NULL}, |
| 1103 | there would be a lot of redundant tests and the code would run slower. |
| 1104 | |
| 1105 | It is better to test for \code{NULL} only at the ``source'', i.e.\ |
| 1106 | when a pointer that may be \code{NULL} is received, e.g.\ from |
| 1107 | \code{malloc()} or from a function that may raise an exception. |
| 1108 | |
| 1109 | The macros \code{Py_INCREF()} and \code{Py_DECREF()} |
| 1110 | don't check for \code{NULL} pointers --- however, their variants |
| 1111 | \code{Py_XINCREF()} and \code{Py_XDECREF()} do. |
| 1112 | |
| 1113 | The macros for checking for a particular object type |
| 1114 | (\code{Py\var{type}_Check()}) don't check for \code{NULL} pointers --- |
| 1115 | again, there is much code that calls several of these in a row to test |
| 1116 | an object against various different expected types, and this would |
| 1117 | generate redundant tests. There are no variants with \code{NULL} |
| 1118 | checking. |
| 1119 | |
| 1120 | The C function calling mechanism guarantees that the argument list |
| 1121 | passed to C functions (\code{args} in the examples) is never |
| 1122 | \code{NULL} --- in fact it guarantees that it is always a tuple.% |
| 1123 | \footnote{These guarantees don't hold when you use the ``old'' style |
| 1124 | calling convention --- this is still found in much existing code.} |
| 1125 | |
| 1126 | It is a severe error to ever let a \code{NULL} pointer ``escape'' to |
| 1127 | the Python user. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1128 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1129 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1130 | \section{Writing Extensions in \Cpp{}} |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1131 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1132 | It is possible to write extension modules in \Cpp{}. Some restrictions |
Guido van Rossum | ed39cd0 | 1995-10-08 00:17:19 +0000 | [diff] [blame] | 1133 | apply. If the main program (the Python interpreter) is compiled and |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1134 | linked by the C compiler, global or static objects with constructors |
Guido van Rossum | ed39cd0 | 1995-10-08 00:17:19 +0000 | [diff] [blame] | 1135 | cannot be used. This is not a problem if the main program is linked |
| 1136 | by the \Cpp{} compiler. All functions that will be called directly or |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1137 | indirectly (i.e. via function pointers) by the Python interpreter will |
| 1138 | have to be declared using \code{extern "C"}; this applies to all |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 1139 | ``methods'' as well as to the module's initialization function. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1140 | It is unnecessary to enclose the Python header files in |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1141 | \code{extern "C" \{...\}} --- they use this form already if the symbol |
| 1142 | \samp{__cplusplus} is defined (all recent C++ compilers define this |
| 1143 | symbol). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1144 | |
| 1145 | \chapter{Embedding Python in another application} |
| 1146 | |
| 1147 | Embedding Python is similar to extending it, but not quite. The |
| 1148 | difference is that when you extend Python, the main program of the |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1149 | application is still the Python interpreter, while if you embed |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1150 | Python, the main program may have nothing to do with Python --- |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1151 | instead, some parts of the application occasionally call the Python |
| 1152 | interpreter to run some Python code. |
| 1153 | |
| 1154 | So if you are embedding Python, you are providing your own main |
| 1155 | program. One of the things this main program has to do is initialize |
| 1156 | the Python interpreter. At the very least, you have to call the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1157 | function \code{Py_Initialize()}. There are optional calls to pass command |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1158 | line arguments to Python. Then later you can call the interpreter |
| 1159 | from any part of the application. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1160 | |
| 1161 | There are several different ways to call the interpreter: you can pass |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1162 | a string containing Python statements to \code{PyRun_SimpleString()}, |
| 1163 | or you can pass a stdio file pointer and a file name (for |
| 1164 | identification in error messages only) to \code{PyRun_SimpleFile()}. You |
| 1165 | can also call the lower-level operations described in the previous |
| 1166 | chapters to construct and use Python objects. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1167 | |
| 1168 | A simple demo of embedding Python can be found in the directory |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1169 | \file{Demo/embed}. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1170 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1171 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1172 | \section{Embedding Python in \Cpp{}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1173 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1174 | It is also possible to embed Python in a \Cpp{} program; precisely how this |
| 1175 | is done will depend on the details of the \Cpp{} system used; in general you |
| 1176 | will need to write the main program in \Cpp{}, and use the \Cpp{} compiler |
| 1177 | to compile and link your program. There is no need to recompile Python |
| 1178 | itself using \Cpp{}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1179 | |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1180 | |
| 1181 | \chapter{Dynamic Loading} |
| 1182 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1183 | On most modern systems it is possible to configure Python to support |
| 1184 | dynamic loading of extension modules implemented in C. When shared |
| 1185 | libraries are used dynamic loading is configured automatically; |
| 1186 | otherwise you have to select it as a build option (see below). Once |
| 1187 | configured, dynamic loading is trivial to use: when a Python program |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1188 | executes \code{import spam}, the search for modules tries to find a |
| 1189 | file \file{spammodule.o} (\file{spammodule.so} when using shared |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1190 | libraries) in the module search path, and if one is found, it is |
| 1191 | loaded into the executing binary and executed. Once loaded, the |
| 1192 | module acts just like a built-in extension module. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1193 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 1194 | The advantages of dynamic loading are twofold: the ``core'' Python |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1195 | binary gets smaller, and users can extend Python with their own |
| 1196 | modules implemented in C without having to build and maintain their |
| 1197 | own copy of the Python interpreter. There are also disadvantages: |
| 1198 | dynamic loading isn't available on all systems (this just means that |
| 1199 | on some systems you have to use static loading), and dynamically |
| 1200 | loading a module that was compiled for a different version of Python |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1201 | (e.g. with a different representation of objects) may dump core. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1202 | |
| 1203 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1204 | \section{Configuring and Building the Interpreter for Dynamic Loading} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1205 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1206 | There are three styles of dynamic loading: one using shared libraries, |
| 1207 | one using SGI IRIX 4 dynamic loading, and one using GNU dynamic |
| 1208 | loading. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1209 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1210 | \subsection{Shared Libraries} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1211 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1212 | The following systems support dynamic loading using shared libraries: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1213 | SunOS 4; Solaris 2; SGI IRIX 5 (but not SGI IRIX 4!); and probably all |
| 1214 | systems derived from SVR4, or at least those SVR4 derivatives that |
| 1215 | support shared libraries (are there any that don't?). |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1216 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1217 | You don't need to do anything to configure dynamic loading on these |
| 1218 | systems --- the \file{configure} detects the presence of the |
| 1219 | \file{<dlfcn.h>} header file and automatically configures dynamic |
| 1220 | loading. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1221 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1222 | \subsection{SGI IRIX 4 Dynamic Loading} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1223 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1224 | Only SGI IRIX 4 supports dynamic loading of modules using SGI dynamic |
| 1225 | loading. (SGI IRIX 5 might also support it but it is inferior to |
| 1226 | using shared libraries so there is no reason to; a small test didn't |
| 1227 | work right away so I gave up trying to support it.) |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1228 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1229 | Before you build Python, you first need to fetch and build the \code{dl} |
| 1230 | package written by Jack Jansen. This is available by anonymous ftp |
| 1231 | from host \file{ftp.cwi.nl}, directory \file{pub/dynload}, file |
| 1232 | \file{dl-1.6.tar.Z}. (The version number may change.) Follow the |
| 1233 | instructions in the package's \file{README} file to build it. |
| 1234 | |
| 1235 | Once you have built \code{dl}, you can configure Python to use it. To |
| 1236 | this end, you run the \file{configure} script with the option |
| 1237 | \code{--with-dl=\var{directory}} where \var{directory} is the absolute |
| 1238 | pathname of the \code{dl} directory. |
| 1239 | |
| 1240 | Now build and install Python as you normally would (see the |
| 1241 | \file{README} file in the toplevel Python directory.) |
| 1242 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1243 | \subsection{GNU Dynamic Loading} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1244 | |
| 1245 | GNU dynamic loading supports (according to its \file{README} file) the |
| 1246 | following hardware and software combinations: VAX (Ultrix), Sun 3 |
| 1247 | (SunOS 3.4 and 4.0), Sparc (SunOS 4.0), Sequent Symmetry (Dynix), and |
| 1248 | Atari ST. There is no reason to use it on a Sparc; I haven't seen a |
| 1249 | Sun 3 for years so I don't know if these have shared libraries or not. |
| 1250 | |
Guido van Rossum | 7e924dd | 1997-02-10 16:51:52 +0000 | [diff] [blame] | 1251 | You need to fetch and build two packages. |
| 1252 | One is GNU DLD. All development of this code has been done with DLD |
| 1253 | version 3.2.3, which is available by anonymous ftp from host |
| 1254 | \file{ftp.cwi.nl}, directory \file{pub/dynload}, file |
| 1255 | \file{dld-3.2.3.tar.Z}. (A more recent version of DLD is available |
| 1256 | via \file{http://www-swiss.ai.mit.edu/~jaffer/DLD.html} but this has |
| 1257 | not been tested.) |
| 1258 | The other package needed is an |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1259 | emulation of Jack Jansen's \code{dl} package that I wrote on top of |
| 1260 | GNU DLD 3.2.3. This is available from the same host and directory, |
Guido van Rossum | 98046b9 | 1997-08-14 19:50:18 +0000 | [diff] [blame^] | 1261 | file \file{dl-dld-1.1.tar.Z}. (The version number may change --- but I doubt |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1262 | it will.) Follow the instructions in each package's \file{README} |
Guido van Rossum | 98046b9 | 1997-08-14 19:50:18 +0000 | [diff] [blame^] | 1263 | file to configure and build them. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1264 | |
| 1265 | Now configure Python. Run the \file{configure} script with the option |
| 1266 | \code{--with-dl-dld=\var{dl-directory},\var{dld-directory}} where |
| 1267 | \var{dl-directory} is the absolute pathname of the directory where you |
| 1268 | have built the \file{dl-dld} package, and \var{dld-directory} is that |
| 1269 | of the GNU DLD package. The Python interpreter you build hereafter |
| 1270 | will support GNU dynamic loading. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1271 | |
| 1272 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1273 | \section{Building a Dynamically Loadable Module} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1274 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1275 | Since there are three styles of dynamic loading, there are also three |
| 1276 | groups of instructions for building a dynamically loadable module. |
| 1277 | Instructions common for all three styles are given first. Assuming |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1278 | your module is called \code{spam}, the source filename must be |
| 1279 | \file{spammodule.c}, so the object name is \file{spammodule.o}. The |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1280 | module must be written as a normal Python extension module (as |
| 1281 | described earlier). |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1282 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1283 | Note that in all cases you will have to create your own Makefile that |
| 1284 | compiles your module file(s). This Makefile will have to pass two |
| 1285 | \samp{-I} arguments to the C compiler which will make it find the |
| 1286 | Python header files. If the Make variable \var{PYTHONTOP} points to |
| 1287 | the toplevel Python directory, your \var{CFLAGS} Make variable should |
| 1288 | contain the options \samp{-I\$(PYTHONTOP) -I\$(PYTHONTOP)/Include}. |
| 1289 | (Most header files are in the \file{Include} subdirectory, but the |
Guido van Rossum | 305ed11 | 1996-08-19 22:59:46 +0000 | [diff] [blame] | 1290 | \file{config.h} header lives in the toplevel directory.) |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1291 | |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1292 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1293 | \subsection{Shared Libraries} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1294 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1295 | You must link the \samp{.o} file to produce a shared library. This is |
| 1296 | done using a special invocation of the \UNIX{} loader/linker, {\em |
| 1297 | ld}(1). Unfortunately the invocation differs slightly per system. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1298 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1299 | On SunOS 4, use |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1300 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1301 | ld spammodule.o -o spammodule.so |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1302 | \end{verbatim}\ecode |
| 1303 | % |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1304 | On Solaris 2, use |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1305 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1306 | ld -G spammodule.o -o spammodule.so |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1307 | \end{verbatim}\ecode |
| 1308 | % |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1309 | On SGI IRIX 5, use |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1310 | \bcode\begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1311 | ld -shared spammodule.o -o spammodule.so |
Guido van Rossum | e47da0a | 1997-07-17 16:34:52 +0000 | [diff] [blame] | 1312 | \end{verbatim}\ecode |
| 1313 | % |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 1314 | On other systems, consult the manual page for \code{ld}(1) to find what |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1315 | flags, if any, must be used. |
| 1316 | |
| 1317 | If your extension module uses system libraries that haven't already |
| 1318 | been linked with Python (e.g. a windowing system), these must be |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 1319 | passed to the \code{ld} command as \samp{-l} options after the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1320 | \samp{.o} file. |
| 1321 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1322 | The resulting file \file{spammodule.so} must be copied into a directory |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1323 | along the Python module search path. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1324 | |
| 1325 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1326 | \subsection{SGI IRIX 4 Dynamic Loading} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1327 | |
Guido van Rossum | 7ec5957 | 1995-04-07 15:35:33 +0000 | [diff] [blame] | 1328 | {\bf IMPORTANT:} You must compile your extension module with the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1329 | additional C flag \samp{-G0} (or \samp{-G 0}). This instruct the |
| 1330 | assembler to generate position-independent code. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1331 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1332 | You don't need to link the resulting \file{spammodule.o} file; just |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1333 | copy it into a directory along the Python module search path. |
| 1334 | |
| 1335 | The first time your extension is loaded, it takes some extra time and |
| 1336 | a few messages may be printed. This creates a file |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1337 | \file{spammodule.ld} which is an image that can be loaded quickly into |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1338 | the Python interpreter process. When a new Python interpreter is |
| 1339 | installed, the \code{dl} package detects this and rebuilds |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1340 | \file{spammodule.ld}. The file \file{spammodule.ld} is placed in the |
| 1341 | directory where \file{spammodule.o} was found, unless this directory is |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1342 | unwritable; in that case it is placed in a temporary |
| 1343 | directory.\footnote{Check the manual page of the \code{dl} package for |
| 1344 | details.} |
| 1345 | |
| 1346 | If your extension modules uses additional system libraries, you must |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1347 | create a file \file{spammodule.libs} in the same directory as the |
| 1348 | \file{spammodule.o}. This file should contain one or more lines with |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1349 | whitespace-separated options that will be passed to the linker --- |
| 1350 | normally only \samp{-l} options or absolute pathnames of libraries |
| 1351 | (\samp{.a} files) should be used. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1352 | |
| 1353 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1354 | \subsection{GNU Dynamic Loading} |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1355 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1356 | Just copy \file{spammodule.o} into a directory along the Python module |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1357 | search path. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1358 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1359 | If your extension modules uses additional system libraries, you must |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1360 | create a file \file{spammodule.libs} in the same directory as the |
| 1361 | \file{spammodule.o}. This file should contain one or more lines with |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1362 | whitespace-separated absolute pathnames of libraries (\samp{.a} |
| 1363 | files). No \samp{-l} options can be used. |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 1364 | |
| 1365 | |
Guido van Rossum | 9231c8f | 1997-05-15 21:43:21 +0000 | [diff] [blame] | 1366 | %\input{extref} |
Guido van Rossum | 267e80d | 1996-08-09 21:01:07 +0000 | [diff] [blame] | 1367 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1368 | \input{ext.ind} |
| 1369 | |
| 1370 | \end{document} |