Fred Drake | 6659c30 | 1998-03-03 22:02:19 +0000 | [diff] [blame] | 1 | \documentclass{manual} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | d358afe | 1998-12-23 05:02:08 +0000 | [diff] [blame] | 3 | % XXX PM explain how to add new types to Python |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 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 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 14 | \maketitle |
| 15 | |
Fred Drake | 9f86b66 | 1998-07-28 21:55:19 +0000 | [diff] [blame] | 16 | \ifhtml |
| 17 | \chapter*{Front Matter\label{front}} |
| 18 | \fi |
| 19 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 20 | \input{copyright} |
| 21 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 22 | %begin{latexonly} |
| 23 | \vspace{1in} |
| 24 | %end{latexonly} |
| 25 | \strong{\large Acknowledgements} |
| 26 | |
| 27 | % XXX This needs to be checked and updated manually before each |
| 28 | % release. |
| 29 | |
| 30 | The following people have contributed sections to this document: Jim |
| 31 | Fulton, Konrad Hinsen, Chris Phoenix, and Neil Schemenauer. |
| 32 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 33 | \begin{abstract} |
| 34 | |
| 35 | \noindent |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 36 | Python is an interpreted, object-oriented programming language. This |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 37 | document describes how to write modules in C or \Cpp{} to extend the |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 38 | Python interpreter with new modules. Those modules can define new |
| 39 | functions but also new object types and their methods. The document |
| 40 | also describes how to embed the Python interpreter in another |
| 41 | application, for use as an extension language. Finally, it shows how |
| 42 | to compile and link extension modules so that they can be loaded |
| 43 | dynamically (at run time) into the interpreter, if the underlying |
| 44 | operating system supports this feature. |
| 45 | |
| 46 | This document assumes basic knowledge about Python. For an informal |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 47 | introduction to the language, see the Python Tutorial. The \emph{Python |
| 48 | Reference Manual} gives a more formal definition of the language. The |
| 49 | \emph{Python Library Reference} documents the existing object types, |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 50 | functions and modules (both built-in and written in Python) that give |
| 51 | the language its wide application range. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 52 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 53 | For a detailed description of the whole Python/C API, see the separate |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 54 | \emph{Python/C API Reference Manual}. |
Guido van Rossum | fdacc58 | 1997-10-07 14:40:16 +0000 | [diff] [blame] | 55 | |
| 56 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 57 | \end{abstract} |
| 58 | |
Fred Drake | 4d4f9e7 | 1998-01-13 22:25:02 +0000 | [diff] [blame] | 59 | \tableofcontents |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 60 | |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 61 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 62 | \chapter{Extending Python with C or \Cpp{} \label{intro}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 63 | |
Guido van Rossum | 6f0132f | 1993-11-19 13:13:22 +0000 | [diff] [blame] | 64 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 65 | It is quite easy to add new built-in modules to Python, if you know |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 66 | how to program in C. Such \dfn{extension modules} can do two things |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 67 | that can't be done directly in Python: they can implement new built-in |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 68 | 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] | 69 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 70 | To support extensions, the Python API (Application Programmers |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 71 | Interface) defines a set of functions, macros and variables that |
| 72 | provide access to most aspects of the Python run-time system. The |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 73 | Python API is incorporated in a C source file by including the header |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 74 | \code{"Python.h"}. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 75 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 76 | The compilation of an extension module depends on its intended use as |
| 77 | 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] | 78 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 79 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 80 | \section{A Simple Example |
| 81 | \label{simpleExample}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 82 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 83 | Let's create an extension module called \samp{spam} (the favorite food |
| 84 | of Monty Python fans...) and let's say we want to create a Python |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 85 | interface to the C library function \cfunction{system()}.\footnote{An |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 86 | interface for this function already exists in the standard module |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 87 | \module{os} --- it was chosen as a simple and straightfoward example.} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 88 | This function takes a null-terminated character string as argument and |
| 89 | returns an integer. We want this function to be callable from Python |
| 90 | as follows: |
| 91 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 92 | \begin{verbatim} |
| 93 | >>> import spam |
| 94 | >>> status = spam.system("ls -l") |
| 95 | \end{verbatim} |
| 96 | |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 97 | Begin by creating a file \file{spammodule.c}. (In general, if a |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 98 | module is called \samp{spam}, the C file containing its implementation |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 99 | is called \file{spammodule.c}; if the module name is very long, like |
| 100 | \samp{spammify}, the module name can be just \file{spammify.c}.) |
| 101 | |
| 102 | The first line of our file can be: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 103 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 104 | \begin{verbatim} |
| 105 | #include "Python.h" |
| 106 | \end{verbatim} |
| 107 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 108 | which pulls in the Python API (you can add a comment describing the |
| 109 | purpose of the module and a copyright notice if you like). |
| 110 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 111 | All user-visible symbols defined by \code{"Python.h"} have a prefix of |
| 112 | \samp{Py} or \samp{PY}, except those defined in standard header files. |
| 113 | For convenience, and since they are used extensively by the Python |
| 114 | interpreter, \code{"Python.h"} includes a few standard header files: |
| 115 | \code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and |
| 116 | \code{<stdlib.h>}. If the latter header file does not exist on your |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 117 | system, it declares the functions \cfunction{malloc()}, |
| 118 | \cfunction{free()} and \cfunction{realloc()} directly. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 119 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 120 | The next thing we add to our module file is the C function that will |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 121 | be called when the Python expression \samp{spam.system(\var{string})} |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 122 | 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] | 123 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 124 | \begin{verbatim} |
| 125 | static PyObject * |
| 126 | spam_system(self, args) |
| 127 | PyObject *self; |
| 128 | PyObject *args; |
| 129 | { |
| 130 | char *command; |
| 131 | int sts; |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 132 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 133 | if (!PyArg_ParseTuple(args, "s", &command)) |
| 134 | return NULL; |
| 135 | sts = system(command); |
| 136 | return Py_BuildValue("i", sts); |
| 137 | } |
| 138 | \end{verbatim} |
| 139 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 140 | There is a straightforward translation from the argument list in |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 141 | Python (e.g.\ the single expression \code{"ls -l"}) to the arguments |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 142 | passed to the C function. The C function always has two arguments, |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 143 | conventionally named \var{self} and \var{args}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 144 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 145 | The \var{self} argument is only used when the C function implements a |
Fred Drake | 9226d8e | 1999-02-22 14:55:46 +0000 | [diff] [blame] | 146 | built-in method, not a function. In the example, \var{self} will |
| 147 | always be a \NULL{} pointer, since we are defining a function, not a |
| 148 | method. (This is done so that the interpreter doesn't have to |
| 149 | understand two different types of C functions.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 150 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 151 | 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] | 152 | containing the arguments. Each item of the tuple corresponds to an |
| 153 | argument in the call's argument list. The arguments are Python |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 154 | objects --- in order to do anything with them in our C function we have |
| 155 | to convert them to C values. The function \cfunction{PyArg_ParseTuple()} |
| 156 | in the Python API checks the argument types and converts them to C |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 157 | values. It uses a template string to determine the required types of |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 158 | the arguments as well as the types of the C variables into which to |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 159 | store the converted values. More about this later. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 160 | |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 161 | \cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 162 | the right type and its components have been stored in the variables |
| 163 | whose addresses are passed. It returns false (zero) if an invalid |
| 164 | argument list was passed. In the latter case it also raises an |
| 165 | appropriate exception by so the calling function can return |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 166 | \NULL{} immediately (as we saw in the example). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 167 | |
| 168 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 169 | \section{Intermezzo: Errors and Exceptions |
| 170 | \label{errors}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 171 | |
| 172 | An important convention throughout the Python interpreter is the |
| 173 | following: when a function fails, it should set an exception condition |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 174 | and return an error value (usually a \NULL{} pointer). Exceptions |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 175 | are stored in a static global variable inside the interpreter; if this |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 176 | variable is \NULL{} no exception has occurred. A second global |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 177 | variable stores the ``associated value'' of the exception (the second |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 178 | argument to \keyword{raise}). A third variable contains the stack |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 179 | traceback in case the error originated in Python code. These three |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 180 | variables are the C equivalents of the Python variables |
Fred Drake | f9918f2 | 1999-02-05 18:30:49 +0000 | [diff] [blame] | 181 | \code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see |
| 182 | the section on module \module{sys} in the \emph{Python Library |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 183 | Reference}). It is important to know about them to understand how |
| 184 | errors are passed around. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 185 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 186 | The Python API defines a number of functions to set various types of |
| 187 | exceptions. |
| 188 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 189 | The most common one is \cfunction{PyErr_SetString()}. Its arguments |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 190 | are an exception object and a C string. The exception object is |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 191 | usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 192 | C string indicates the cause of the error and is converted to a |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 193 | Python string object and stored as the ``associated value'' of the |
| 194 | exception. |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 195 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 196 | Another useful function is \cfunction{PyErr_SetFromErrno()}, which only |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 197 | takes an exception argument and constructs the associated value by |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 198 | inspection of the (\UNIX{}) global variable \cdata{errno}. The most |
| 199 | general function is \cfunction{PyErr_SetObject()}, which takes two object |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 200 | arguments, the exception and its associated value. You don't need to |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 201 | \cfunction{Py_INCREF()} the objects passed to any of these functions. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 202 | |
| 203 | You can test non-destructively whether an exception has been set with |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 204 | \cfunction{PyErr_Occurred()}. This returns the current exception object, |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 205 | or \NULL{} if no exception has occurred. You normally don't need |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 206 | to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 207 | 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] | 208 | |
Guido van Rossum | d16ddb6 | 1996-12-13 02:38:17 +0000 | [diff] [blame] | 209 | 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] | 210 | that the latter fails, \var{f} should itself return an error value |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 211 | (e.g.\ \NULL{} or \code{-1}). It should \emph{not} call one of the |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 212 | \cfunction{PyErr_*()} functions --- one has already been called by \var{g}. |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 213 | \var{f}'s caller is then supposed to also return an error indication |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 214 | to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()}, |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 215 | and so on --- the most detailed cause of the error was already |
| 216 | reported by the function that first detected it. Once the error |
| 217 | reaches the Python interpreter's main loop, this aborts the currently |
| 218 | executing Python code and tries to find an exception handler specified |
| 219 | by the Python programmer. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 220 | |
| 221 | (There are situations where a module can actually give a more detailed |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 222 | error message by calling another \cfunction{PyErr_*()} function, and in |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 223 | such cases it is fine to do so. As a general rule, however, this is |
| 224 | not necessary, and can cause information about the cause of the error |
| 225 | 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] | 226 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 227 | To ignore an exception set by a function call that failed, the exception |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 228 | condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}. |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 229 | The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 230 | want to pass the error on to the interpreter but wants to handle it |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 231 | completely by itself (e.g.\ by trying something else or pretending |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 232 | nothing happened). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 233 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 234 | Note that a failing \cfunction{malloc()} call must be turned into an |
| 235 | exception --- the direct caller of \cfunction{malloc()} (or |
| 236 | \cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and |
| 237 | return a failure indicator itself. All the object-creating functions |
| 238 | (\cfunction{PyInt_FromLong()} etc.) already do this, so only if you |
| 239 | call \cfunction{malloc()} directly this note is of importance. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 240 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 241 | Also note that, with the important exception of |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 242 | \cfunction{PyArg_ParseTuple()} and friends, functions that return an |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 243 | integer status usually return a positive value or zero for success and |
| 244 | \code{-1} for failure, like \UNIX{} system calls. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 245 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 246 | Finally, be careful to clean up garbage (by making |
| 247 | \cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects |
| 248 | you have already created) when you return an error indicator! |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 249 | |
| 250 | The choice of which exception to raise is entirely yours. There are |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 251 | predeclared C objects corresponding to all built-in Python exceptions, |
Fred Drake | abfd7d6 | 1999-02-16 17:34:51 +0000 | [diff] [blame] | 252 | e.g.\ \cdata{PyExc_ZeroDivisionError}, which you can use directly. Of |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 253 | course, you should choose exceptions wisely --- don't use |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 254 | \cdata{PyExc_TypeError} to mean that a file couldn't be opened (that |
| 255 | should probably be \cdata{PyExc_IOError}). If something's wrong with |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 256 | the argument list, the \cfunction{PyArg_ParseTuple()} function usually |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 257 | raises \cdata{PyExc_TypeError}. If you have an argument whose value |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 258 | must be in a particular range or must satisfy other conditions, |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 259 | \cdata{PyExc_ValueError} is appropriate. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 260 | |
| 261 | You can also define a new exception that is unique to your module. |
| 262 | For this, you usually declare a static object variable at the |
| 263 | beginning of your file, e.g. |
| 264 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 265 | \begin{verbatim} |
| 266 | static PyObject *SpamError; |
| 267 | \end{verbatim} |
| 268 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 269 | and initialize it in your module's initialization function |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 270 | (\cfunction{initspam()}) with an exception object, e.g.\ (leaving out |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 271 | the error checking for now): |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 272 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 273 | \begin{verbatim} |
| 274 | void |
| 275 | initspam() |
| 276 | { |
| 277 | PyObject *m, *d; |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 278 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 279 | m = Py_InitModule("spam", SpamMethods); |
| 280 | d = PyModule_GetDict(m); |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 281 | SpamError = PyErr_NewException("spam.error", NULL, NULL); |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 282 | PyDict_SetItemString(d, "error", SpamError); |
| 283 | } |
| 284 | \end{verbatim} |
| 285 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 286 | Note that the Python name for the exception object is |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 287 | \exception{spam.error}. The \cfunction{PyErr_NewException()} function |
| 288 | may create either a string or class, depending on whether the |
| 289 | \samp{-X} flag was passed to the interpreter. If \samp{-X} was used, |
| 290 | \cdata{SpamError} will be a string object, otherwise it will be a |
| 291 | class object with the base class being \exception{Exception}, |
| 292 | described in the \emph{Python Library Reference} under ``Built-in |
| 293 | Exceptions.'' |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 294 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 295 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 296 | \section{Back to the Example |
| 297 | \label{backToExample}} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 298 | |
| 299 | Going back to our example function, you should now be able to |
| 300 | understand this statement: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 301 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 302 | \begin{verbatim} |
| 303 | if (!PyArg_ParseTuple(args, "s", &command)) |
| 304 | return NULL; |
| 305 | \end{verbatim} |
| 306 | |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 307 | It returns \NULL{} (the error indicator for functions returning |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 308 | object pointers) if an error is detected in the argument list, relying |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 309 | on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 310 | string value of the argument has been copied to the local variable |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 311 | \cdata{command}. This is a pointer assignment and you are not supposed |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 312 | to modify the string to which it points (so in Standard C, the variable |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 313 | \cdata{command} should properly be declared as \samp{const char |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 314 | *command}). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 315 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 316 | The next statement is a call to the \UNIX{} function |
| 317 | \cfunction{system()}, passing it the string we just got from |
| 318 | \cfunction{PyArg_ParseTuple()}: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 319 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 320 | \begin{verbatim} |
| 321 | sts = system(command); |
| 322 | \end{verbatim} |
| 323 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 324 | Our \function{spam.system()} function must return the value of |
| 325 | \cdata{sts} as a Python object. This is done using the function |
| 326 | \cfunction{Py_BuildValue()}, which is something like the inverse of |
| 327 | \cfunction{PyArg_ParseTuple()}: it takes a format string and an |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 328 | arbitrary number of C values, and returns a new Python object. |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 329 | More info on \cfunction{Py_BuildValue()} is given later. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 330 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 331 | \begin{verbatim} |
| 332 | return Py_BuildValue("i", sts); |
| 333 | \end{verbatim} |
| 334 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 335 | In this case, it will return an integer object. (Yes, even integers |
| 336 | are objects on the heap in Python!) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 337 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 338 | If you have a C function that returns no useful argument (a function |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 339 | returning \ctype{void}), the corresponding Python function must return |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 340 | \code{None}. You need this idiom to do so: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 341 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 342 | \begin{verbatim} |
| 343 | Py_INCREF(Py_None); |
| 344 | return Py_None; |
| 345 | \end{verbatim} |
| 346 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 347 | \cdata{Py_None} is the C name for the special Python object |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 348 | \code{None}. It is a genuine Python object rather than a \NULL{} |
| 349 | pointer, which means ``error'' in most contexts, as we have seen. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 350 | |
| 351 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 352 | \section{The Module's Method Table and Initialization Function |
| 353 | \label{methodTable}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 354 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 355 | I promised to show how \cfunction{spam_system()} is called from Python |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 356 | programs. First, we need to list its name and address in a ``method |
| 357 | table'': |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 358 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 359 | \begin{verbatim} |
| 360 | static PyMethodDef SpamMethods[] = { |
| 361 | ... |
| 362 | {"system", spam_system, METH_VARARGS}, |
| 363 | ... |
| 364 | {NULL, NULL} /* Sentinel */ |
| 365 | }; |
| 366 | \end{verbatim} |
| 367 | |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 368 | Note the third entry (\samp{METH_VARARGS}). This is a flag telling |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 369 | the interpreter the calling convention to be used for the C |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 370 | function. It should normally always be \samp{METH_VARARGS} or |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 371 | \samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 372 | obsolete variant of \cfunction{PyArg_ParseTuple()} is used. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 373 | |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 374 | When using only \samp{METH_VARARGS}, the function should expect |
| 375 | the Python-level parameters to be passed in as a tuple acceptable for |
| 376 | parsing via \cfunction{PyArg_ParseTuple()}; more information on this |
| 377 | function is provided below. |
| 378 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 379 | The \constant{METH_KEYWORDS} bit may be set in the third field if keyword |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 380 | arguments should be passed to the function. In this case, the C |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 381 | function should accept a third \samp{PyObject *} parameter which will |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 382 | be a dictionary of keywords. Use \cfunction{PyArg_ParseTupleAndKeywords()} |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 383 | to parse the arguments to such a function. |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 384 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 385 | The method table must be passed to the interpreter in the module's |
| 386 | initialization function (which should be the only non-\code{static} |
| 387 | item defined in the module file): |
| 388 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 389 | \begin{verbatim} |
| 390 | void |
| 391 | initspam() |
| 392 | { |
| 393 | (void) Py_InitModule("spam", SpamMethods); |
| 394 | } |
| 395 | \end{verbatim} |
| 396 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 397 | When the Python program imports module \module{spam} for the first |
| 398 | time, \cfunction{initspam()} is called. It calls |
| 399 | \cfunction{Py_InitModule()}, which creates a ``module object'' (which |
| 400 | is inserted in the dictionary \code{sys.modules} under the key |
| 401 | \code{"spam"}), and inserts built-in function objects into the newly |
| 402 | created module based upon the table (an array of \ctype{PyMethodDef} |
| 403 | structures) that was passed as its second argument. |
| 404 | \cfunction{Py_InitModule()} returns a pointer to the module object |
| 405 | that it creates (which is unused here). It aborts with a fatal error |
| 406 | if the module could not be initialized satisfactorily, so the caller |
| 407 | doesn't need to check for errors. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 408 | |
| 409 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 410 | \section{Compilation and Linkage |
| 411 | \label{compilation}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 412 | |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 413 | There are two more things to do before you can use your new extension: |
| 414 | compiling and linking it with the Python system. If you use dynamic |
| 415 | loading, the details depend on the style of dynamic loading your |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 416 | system uses; see the chapter ``Dynamic Loading'' for more information |
| 417 | about this. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 418 | |
| 419 | If you can't use dynamic loading, or if you want to make your module a |
| 420 | 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] | 421 | configuration setup and rebuild the interpreter. Luckily, this is |
| 422 | very simple: just place your file (\file{spammodule.c} for example) in |
Fred Drake | a4a90dd | 1999-04-29 02:44:50 +0000 | [diff] [blame] | 423 | the \file{Modules/} directory of an unpacked source distribution, add |
| 424 | a line to the file \file{Modules/Setup.local} describing your file: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 425 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 426 | \begin{verbatim} |
| 427 | spam spammodule.o |
| 428 | \end{verbatim} |
| 429 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 430 | and rebuild the interpreter by running \program{make} in the toplevel |
Fred Drake | a4a90dd | 1999-04-29 02:44:50 +0000 | [diff] [blame] | 431 | directory. You can also run \program{make} in the \file{Modules/} |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 432 | subdirectory, but then you must first rebuild \file{Makefile} |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 433 | there by running `\program{make} Makefile'. (This is necessary each |
| 434 | time you change the \file{Setup} file.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 435 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 436 | If your module requires additional libraries to link with, these can |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 437 | be listed on the line in the configuration file as well, for instance: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 438 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 439 | \begin{verbatim} |
| 440 | spam spammodule.o -lX11 |
| 441 | \end{verbatim} |
| 442 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 443 | \section{Calling Python Functions from C |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 444 | \label{callingPython}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 445 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 446 | So far we have concentrated on making C functions callable from |
| 447 | Python. The reverse is also useful: calling Python functions from C. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 448 | This is especially the case for libraries that support so-called |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 449 | ``callback'' functions. If a C interface makes use of callbacks, the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 450 | equivalent Python often needs to provide a callback mechanism to the |
| 451 | Python programmer; the implementation will require calling the Python |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 452 | callback functions from a C callback. Other uses are also imaginable. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 453 | |
| 454 | Fortunately, the Python interpreter is easily called recursively, and |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 455 | 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] | 456 | 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] | 457 | input --- if you're interested, have a look at the implementation of |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 458 | the \samp{-c} command line option in \file{Python/pythonmain.c} from |
| 459 | the Python source code.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 460 | |
| 461 | Calling a Python function is easy. First, the Python program must |
| 462 | somehow pass you the Python function object. You should provide a |
| 463 | function (or some other interface) to do this. When this function is |
| 464 | called, save a pointer to the Python function object (be careful to |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 465 | \cfunction{Py_INCREF()} it!) in a global variable --- or wherever you |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 466 | see fit. For example, the following function might be part of a module |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 467 | definition: |
| 468 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 469 | \begin{verbatim} |
| 470 | static PyObject *my_callback = NULL; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 471 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 472 | static PyObject * |
| 473 | my_set_callback(dummy, arg) |
| 474 | PyObject *dummy, *arg; |
| 475 | { |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 476 | PyObject *result = NULL; |
| 477 | PyObject *temp; |
| 478 | |
| 479 | if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { |
| 480 | if (!PyCallable_Check(temp)) { |
| 481 | PyErr_SetString(PyExc_TypeError, "parameter must be callable"); |
| 482 | return NULL; |
| 483 | } |
| 484 | Py_XINCREF(temp); /* Add a reference to new callback */ |
| 485 | Py_XDECREF(my_callback); /* Dispose of previous callback */ |
| 486 | my_callback = temp; /* Remember new callback */ |
| 487 | /* Boilerplate to return "None" */ |
| 488 | Py_INCREF(Py_None); |
| 489 | result = Py_None; |
| 490 | } |
| 491 | return result; |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 492 | } |
| 493 | \end{verbatim} |
| 494 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 495 | This function must be registered with the interpreter using the |
Fred Drake | 5f342ac | 1999-04-29 02:47:40 +0000 | [diff] [blame] | 496 | \constant{METH_VARARGS} flag; this is described in section |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 497 | \ref{methodTable}, ``The Module's Method Table and Initialization |
| 498 | Function.'' The \cfunction{PyArg_ParseTuple()} function and its |
Fred Drake | 5f342ac | 1999-04-29 02:47:40 +0000 | [diff] [blame] | 499 | arguments are documented in section \ref{parseTuple}, ``Format Strings |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 500 | for \cfunction{PyArg_ParseTuple()}.'' |
| 501 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 502 | The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} |
| 503 | increment/decrement the reference count of an object and are safe in |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 504 | the presence of \NULL{} pointers (but note that \var{temp} will not be |
Fred Drake | 5f342ac | 1999-04-29 02:47:40 +0000 | [diff] [blame] | 505 | \NULL{} in this context). More info on them in section |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 506 | \ref{refcounts}, ``Reference Counts.'' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 507 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 508 | Later, when it is time to call the function, you call the C function |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 509 | \cfunction{PyEval_CallObject()}. This function has two arguments, both |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 510 | pointers to arbitrary Python objects: the Python function, and the |
| 511 | argument list. The argument list must always be a tuple object, whose |
| 512 | length is the number of arguments. To call the Python function with |
| 513 | no arguments, pass an empty tuple; to call it with one argument, pass |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 514 | a singleton tuple. \cfunction{Py_BuildValue()} returns a tuple when its |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 515 | format string consists of zero or more format codes between |
| 516 | parentheses. For example: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 517 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 518 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 519 | int arg; |
| 520 | PyObject *arglist; |
| 521 | PyObject *result; |
| 522 | ... |
| 523 | arg = 123; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 524 | ... |
| 525 | /* Time to call the callback */ |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 526 | arglist = Py_BuildValue("(i)", arg); |
| 527 | result = PyEval_CallObject(my_callback, arglist); |
| 528 | Py_DECREF(arglist); |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 529 | \end{verbatim} |
| 530 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 531 | \cfunction{PyEval_CallObject()} returns a Python object pointer: this is |
| 532 | the return value of the Python function. \cfunction{PyEval_CallObject()} is |
Guido van Rossum | b92112d | 1995-03-20 14:24:09 +0000 | [diff] [blame] | 533 | ``reference-count-neutral'' with respect to its arguments. In the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 534 | example a new tuple was created to serve as the argument list, which |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 535 | is \cfunction{Py_DECREF()}-ed immediately after the call. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 536 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 537 | The return value of \cfunction{PyEval_CallObject()} is ``new'': either it |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 538 | is a brand new object, or it is an existing object whose reference |
| 539 | count has been incremented. So, unless you want to save it in a |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 540 | global variable, you should somehow \cfunction{Py_DECREF()} the result, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 541 | even (especially!) if you are not interested in its value. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 542 | |
| 543 | Before you do this, however, it is important to check that the return |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 544 | value isn't \NULL{}. If it is, the Python function terminated by |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 545 | raising an exception. If the C code that called |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 546 | \cfunction{PyEval_CallObject()} is called from Python, it should now |
| 547 | return an error indication to its Python caller, so the interpreter |
| 548 | can print a stack trace, or the calling Python code can handle the |
| 549 | exception. If this is not possible or desirable, the exception should |
| 550 | be cleared by calling \cfunction{PyErr_Clear()}. For example: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 551 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 552 | \begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 553 | if (result == NULL) |
| 554 | return NULL; /* Pass error back */ |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 555 | ...use result... |
| 556 | Py_DECREF(result); |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 557 | \end{verbatim} |
| 558 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 559 | Depending on the desired interface to the Python callback function, |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 560 | you may also have to provide an argument list to |
| 561 | \cfunction{PyEval_CallObject()}. In some cases the argument list is |
| 562 | also provided by the Python program, through the same interface that |
| 563 | specified the callback function. It can then be saved and used in the |
| 564 | same manner as the function object. In other cases, you may have to |
| 565 | construct a new tuple to pass as the argument list. The simplest way |
| 566 | to do this is to call \cfunction{Py_BuildValue()}. For example, if |
| 567 | you want to pass an integral event code, you might use the following |
| 568 | code: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 569 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 570 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 571 | PyObject *arglist; |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 572 | ... |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 573 | arglist = Py_BuildValue("(l)", eventcode); |
| 574 | result = PyEval_CallObject(my_callback, arglist); |
| 575 | Py_DECREF(arglist); |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 576 | if (result == NULL) |
| 577 | return NULL; /* Pass error back */ |
| 578 | /* Here maybe use the result */ |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 579 | Py_DECREF(result); |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 580 | \end{verbatim} |
| 581 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 582 | Note the placement of \samp{Py_DECREF(arglist)} immediately after the |
| 583 | call, before the error check! Also note that strictly spoken this |
| 584 | code is not complete: \cfunction{Py_BuildValue()} may run out of |
| 585 | memory, and this should be checked. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 586 | |
| 587 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 588 | \section{Format Strings for \cfunction{PyArg_ParseTuple()} |
| 589 | \label{parseTuple}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 590 | |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 591 | The \cfunction{PyArg_ParseTuple()} function is declared as follows: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 592 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 593 | \begin{verbatim} |
| 594 | int PyArg_ParseTuple(PyObject *arg, char *format, ...); |
| 595 | \end{verbatim} |
| 596 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 597 | The \var{arg} argument must be a tuple object containing an argument |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 598 | list passed from Python to a C function. The \var{format} argument |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 599 | must be a format string, whose syntax is explained below. The |
| 600 | remaining arguments must be addresses of variables whose type is |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 601 | determined by the format string. For the conversion to succeed, the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 602 | \var{arg} object must match the format and the format must be |
| 603 | exhausted. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 604 | |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 605 | Note that while \cfunction{PyArg_ParseTuple()} checks that the Python |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 606 | arguments have the required types, it cannot check the validity of the |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 607 | addresses of C variables passed to the call: if you make mistakes |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 608 | there, your code will probably crash or at least overwrite random bits |
| 609 | in memory. So be careful! |
| 610 | |
| 611 | A format string consists of zero or more ``format units''. A format |
| 612 | unit describes one Python object; it is usually a single character or |
| 613 | a parenthesized sequence of format units. With a few exceptions, a |
| 614 | format unit that is not a parenthesized sequence normally corresponds |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 615 | to a single address argument to \cfunction{PyArg_ParseTuple()}. In the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 616 | following description, the quoted form is the format unit; the entry |
| 617 | in (round) parentheses is the Python object type that matches the |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 618 | format unit; and the entry in [square] brackets is the type of the C |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 619 | variable(s) whose address should be passed. (Use the \samp{\&} |
| 620 | operator to pass a variable's address.) |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 621 | |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 622 | \begin{description} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 623 | |
Fred Drake | 3fe985f | 1998-03-04 03:51:42 +0000 | [diff] [blame] | 624 | \item[\samp{s} (string) {[char *]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 625 | Convert a Python string to a C pointer to a character string. You |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 626 | must not provide storage for the string itself; a pointer to an |
| 627 | existing string is stored into the character pointer variable whose |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 628 | address you pass. The C string is null-terminated. The Python string |
Fred Drake | 3da06a6 | 1998-02-26 18:49:12 +0000 | [diff] [blame] | 629 | must not contain embedded null bytes; if it does, a \exception{TypeError} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 630 | exception is raised. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 631 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 632 | \item[\samp{s\#} (string) {[char *, int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 633 | This variant on \samp{s} stores into two C variables, the first one |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 634 | a pointer to a character string, the second one its length. In this |
| 635 | case the Python string may contain embedded null bytes. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 636 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 637 | \item[\samp{z} (string or \code{None}) {[char *]}] |
| 638 | Like \samp{s}, but the Python object may also be \code{None}, in which |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 639 | case the C pointer is set to \NULL{}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 640 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 641 | \item[\samp{z\#} (string or \code{None}) {[char *, int]}] |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 642 | This is to \samp{s\#} as \samp{z} is to \samp{s}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 643 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 644 | \item[\samp{b} (integer) {[char]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 645 | Convert a Python integer to a tiny int, stored in a C \ctype{char}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 646 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 647 | \item[\samp{h} (integer) {[short int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 648 | Convert a Python integer to a C \ctype{short int}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 649 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 650 | \item[\samp{i} (integer) {[int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 651 | Convert a Python integer to a plain C \ctype{int}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 652 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 653 | \item[\samp{l} (integer) {[long int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 654 | Convert a Python integer to a C \ctype{long int}. |
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 | \item[\samp{c} (string of length 1) {[char]}] |
| 657 | Convert a Python character, represented as a string of length 1, to a |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 658 | C \ctype{char}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 659 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 660 | \item[\samp{f} (float) {[float]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 661 | Convert a Python floating point number to a C \ctype{float}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 662 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 663 | \item[\samp{d} (float) {[double]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 664 | Convert a Python floating point number to a C \ctype{double}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 665 | |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 666 | \item[\samp{D} (complex) {[Py_complex]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 667 | Convert a Python complex number to a C \ctype{Py_complex} structure. |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 668 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 669 | \item[\samp{O} (object) {[PyObject *]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 670 | Store a Python object (without any conversion) in a C object pointer. |
| 671 | The C program thus receives the actual object that was passed. The |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 672 | object's reference count is not increased. The pointer stored is not |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 673 | \NULL{}. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 674 | |
Fred Drake | 3fe985f | 1998-03-04 03:51:42 +0000 | [diff] [blame] | 675 | \item[\samp{O!} (object) {[\var{typeobject}, PyObject *]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 676 | Store a Python object in a C object pointer. This is similar to |
| 677 | \samp{O}, but takes two C arguments: the first is the address of a |
| 678 | Python type object, the second is the address of the C variable (of |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 679 | type \ctype{PyObject *}) into which the object pointer is stored. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 680 | If the Python object does not have the required type, a |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 681 | \exception{TypeError} exception is raised. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 682 | |
Fred Drake | 3fe985f | 1998-03-04 03:51:42 +0000 | [diff] [blame] | 683 | \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 684 | Convert a Python object to a C variable through a \var{converter} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 685 | function. This takes two arguments: the first is a function, the |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 686 | second is the address of a C variable (of arbitrary type), converted |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 687 | to \ctype{void *}. The \var{converter} function in turn is called as |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 688 | follows: |
| 689 | |
| 690 | \code{\var{status} = \var{converter}(\var{object}, \var{address});} |
| 691 | |
| 692 | where \var{object} is the Python object to be converted and |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 693 | \var{address} is the \ctype{void *} argument that was passed to |
| 694 | \cfunction{PyArg_ConvertTuple()}. The returned \var{status} should be |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 695 | \code{1} for a successful conversion and \code{0} if the conversion |
| 696 | has failed. When the conversion fails, the \var{converter} function |
| 697 | should raise an exception. |
| 698 | |
| 699 | \item[\samp{S} (string) {[PyStringObject *]}] |
Guido van Rossum | 2474d68 | 1998-02-26 17:07:11 +0000 | [diff] [blame] | 700 | Like \samp{O} but requires that the Python object is a string object. |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 701 | Raises a \exception{TypeError} exception if the object is not a string |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 702 | object. The C variable may also be declared as \ctype{PyObject *}. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 703 | |
Fred Drake | 3fe985f | 1998-03-04 03:51:42 +0000 | [diff] [blame] | 704 | \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}] |
Fred Drake | 29fb54f | 1999-02-18 03:50:01 +0000 | [diff] [blame] | 705 | The object must be a Python sequence whose length is the number of |
| 706 | format units in \var{items}. The C arguments must correspond to the |
| 707 | individual format units in \var{items}. Format units for sequences |
| 708 | may be nested. |
| 709 | |
| 710 | \strong{Note:} Prior to Python version 1.5.2, this format specifier |
| 711 | only accepted a tuple containing the individual parameters, not an |
| 712 | arbitrary sequence. Code which previously caused a |
| 713 | \exception{TypeError} to be raised here may now proceed without an |
| 714 | exception. This is not expected to be a problem for existing code. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 715 | |
| 716 | \end{description} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 717 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 718 | It is possible to pass Python long integers where integers are |
Fred Drake | 1aedbd8 | 1998-02-16 14:47:27 +0000 | [diff] [blame] | 719 | requested; however no proper range checking is done --- the most |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 720 | significant bits are silently truncated when the receiving field is |
| 721 | too small to receive the value (actually, the semantics are inherited |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 722 | from downcasts in C --- your mileage may vary). |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 723 | |
| 724 | A few other characters have a meaning in a format string. These may |
| 725 | not occur inside nested parentheses. They are: |
| 726 | |
| 727 | \begin{description} |
| 728 | |
| 729 | \item[\samp{|}] |
| 730 | Indicates that the remaining arguments in the Python argument list are |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 731 | optional. The C variables corresponding to optional arguments should |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 732 | be initialized to their default value --- when an optional argument is |
Fred Drake | 40e72f7 | 1998-03-03 19:37:38 +0000 | [diff] [blame] | 733 | not specified, \cfunction{PyArg_ParseTuple()} does not touch the contents |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 734 | of the corresponding C variable(s). |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 735 | |
| 736 | \item[\samp{:}] |
| 737 | The list of format units ends here; the string after the colon is used |
| 738 | as the function name in error messages (the ``associated value'' of |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 739 | the exception that \cfunction{PyArg_ParseTuple()} raises). |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 740 | |
| 741 | \item[\samp{;}] |
| 742 | The list of format units ends here; the string after the colon is used |
| 743 | as the error message \emph{instead} of the default error message. |
| 744 | Clearly, \samp{:} and \samp{;} mutually exclude each other. |
| 745 | |
| 746 | \end{description} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 747 | |
| 748 | Some example calls: |
| 749 | |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 750 | \begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 751 | int ok; |
| 752 | int i, j; |
| 753 | long k, l; |
| 754 | char *s; |
| 755 | int size; |
| 756 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 757 | ok = PyArg_ParseTuple(args, ""); /* No arguments */ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 758 | /* Python call: f() */ |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 759 | \end{verbatim} |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 760 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 761 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 762 | ok = PyArg_ParseTuple(args, "s", &s); /* A string */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 763 | /* Possible Python call: f('whoops!') */ |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 764 | \end{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 765 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 766 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 767 | 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] | 768 | /* Possible Python call: f(1, 2, 'three') */ |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 769 | \end{verbatim} |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 770 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 771 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 772 | ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 773 | /* 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] | 774 | /* Possible Python call: f((1, 2), 'three') */ |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 775 | \end{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 776 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 777 | \begin{verbatim} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 778 | { |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 779 | char *file; |
| 780 | char *mode = "r"; |
| 781 | int bufsize = 0; |
| 782 | ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); |
| 783 | /* A string, and optionally another string and an integer */ |
| 784 | /* Possible Python calls: |
| 785 | f('spam') |
| 786 | f('spam', 'w') |
| 787 | f('spam', 'wb', 100000) */ |
| 788 | } |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 789 | \end{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 790 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 791 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 792 | { |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 793 | int left, top, right, bottom, h, v; |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 794 | ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 795 | &left, &top, &right, &bottom, &h, &v); |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 796 | /* A rectangle and a point */ |
| 797 | /* Possible Python call: |
| 798 | f(((0, 0), (400, 300)), (10, 10)) */ |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 799 | } |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 800 | \end{verbatim} |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 801 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 802 | \begin{verbatim} |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 803 | { |
| 804 | Py_complex c; |
| 805 | ok = PyArg_ParseTuple(args, "D:myfunction", &c); |
| 806 | /* a complex, also providing a function name for errors */ |
| 807 | /* Possible Python call: myfunction(1+2j) */ |
| 808 | } |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 809 | \end{verbatim} |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 810 | |
| 811 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 812 | \section{Keyword Parsing with \cfunction{PyArg_ParseTupleAndKeywords()} |
| 813 | \label{parseTupleAndKeywords}} |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 814 | |
| 815 | The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as |
| 816 | follows: |
| 817 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 818 | \begin{verbatim} |
| 819 | int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, |
| 820 | char *format, char **kwlist, ...); |
| 821 | \end{verbatim} |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 822 | |
| 823 | The \var{arg} and \var{format} parameters are identical to those of the |
| 824 | \cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter |
| 825 | is the dictionary of keywords received as the third parameter from the |
| 826 | Python runtime. The \var{kwlist} parameter is a \NULL{}-terminated |
| 827 | list of strings which identify the parameters; the names are matched |
| 828 | with the type information from \var{format} from left to right. |
| 829 | |
| 830 | \strong{Note:} Nested tuples cannot be parsed when using keyword |
| 831 | arguments! Keyword parameters passed in which are not present in the |
Fred Drake | cd05ca9 | 1998-03-07 05:32:08 +0000 | [diff] [blame] | 832 | \var{kwlist} will cause \exception{TypeError} to be raised. |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 833 | |
| 834 | Here is an example module which uses keywords, based on an example by |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 835 | Geoff Philbrick (\email{philbrick@hks.com}):% |
| 836 | \index{Philbrick, Geoff} |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 837 | |
| 838 | \begin{verbatim} |
| 839 | #include <stdio.h> |
| 840 | #include "Python.h" |
| 841 | |
| 842 | static PyObject * |
| 843 | keywdarg_parrot(self, args, keywds) |
| 844 | PyObject *self; |
| 845 | PyObject *args; |
| 846 | PyObject *keywds; |
| 847 | { |
| 848 | int voltage; |
| 849 | char *state = "a stiff"; |
| 850 | char *action = "voom"; |
| 851 | char *type = "Norwegian Blue"; |
| 852 | |
| 853 | static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; |
| 854 | |
| 855 | if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, |
| 856 | &voltage, &state, &action, &type)) |
| 857 | return NULL; |
| 858 | |
| 859 | printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", |
| 860 | action, voltage); |
| 861 | printf("-- Lovely plumage, the %s -- It's %s!\n", type, state); |
| 862 | |
| 863 | Py_INCREF(Py_None); |
| 864 | |
| 865 | return Py_None; |
| 866 | } |
| 867 | |
| 868 | static PyMethodDef keywdarg_methods[] = { |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 869 | /* The cast of the function is necessary since PyCFunction values |
| 870 | * only take two PyObject* parameters, and keywdarg_parrot() takes |
| 871 | * three. |
| 872 | */ |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 873 | {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS|METH_KEYWORDS}, |
| 874 | {NULL, NULL} /* sentinel */ |
| 875 | }; |
| 876 | |
| 877 | void |
| 878 | initkeywdarg() |
| 879 | { |
| 880 | /* Create the module and add the functions */ |
Fred Drake | cd05ca9 | 1998-03-07 05:32:08 +0000 | [diff] [blame] | 881 | Py_InitModule("keywdarg", keywdarg_methods); |
Fred Drake | b6e5032 | 1998-02-04 20:26:31 +0000 | [diff] [blame] | 882 | } |
| 883 | \end{verbatim} |
| 884 | |
| 885 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 886 | \section{The \cfunction{Py_BuildValue()} Function |
| 887 | \label{buildValue}} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 888 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 889 | This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 890 | declared as follows: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 891 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 892 | \begin{verbatim} |
| 893 | PyObject *Py_BuildValue(char *format, ...); |
| 894 | \end{verbatim} |
| 895 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 896 | It recognizes a set of format units similar to the ones recognized by |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 897 | \cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 898 | function, not output) must not be pointers, just values. It returns a |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 899 | new Python object, suitable for returning from a C function called |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 900 | from Python. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 901 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 902 | One difference with \cfunction{PyArg_ParseTuple()}: while the latter |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 903 | requires its first argument to be a tuple (since Python argument lists |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 904 | are always represented as tuples internally), |
| 905 | \cfunction{Py_BuildValue()} does not always build a tuple. It builds |
| 906 | a tuple only if its format string contains two or more format units. |
| 907 | If the format string is empty, it returns \code{None}; if it contains |
| 908 | exactly one format unit, it returns whatever object is described by |
| 909 | that format unit. To force it to return a tuple of size 0 or one, |
| 910 | parenthesize the format string. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 911 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 912 | In the following description, the quoted form is the format unit; the |
| 913 | entry in (round) parentheses is the Python object type that the format |
| 914 | unit will return; and the entry in [square] brackets is the type of |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 915 | the C value(s) to be passed. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 916 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 917 | The characters space, tab, colon and comma are ignored in format |
| 918 | strings (but not within format units such as \samp{s\#}). This can be |
| 919 | used to make long format strings a tad more readable. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 920 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 921 | \begin{description} |
| 922 | |
| 923 | \item[\samp{s} (string) {[char *]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 924 | Convert a null-terminated C string to a Python object. If the C |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 925 | string pointer is \NULL{}, \code{None} is returned. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 926 | |
| 927 | \item[\samp{s\#} (string) {[char *, int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 928 | Convert a C string and its length to a Python object. If the C string |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 929 | pointer is \NULL{}, the length is ignored and \code{None} is |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 930 | returned. |
| 931 | |
| 932 | \item[\samp{z} (string or \code{None}) {[char *]}] |
| 933 | Same as \samp{s}. |
| 934 | |
| 935 | \item[\samp{z\#} (string or \code{None}) {[char *, int]}] |
| 936 | Same as \samp{s\#}. |
| 937 | |
| 938 | \item[\samp{i} (integer) {[int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 939 | Convert a plain C \ctype{int} to a Python integer object. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 940 | |
| 941 | \item[\samp{b} (integer) {[char]}] |
| 942 | Same as \samp{i}. |
| 943 | |
| 944 | \item[\samp{h} (integer) {[short int]}] |
| 945 | Same as \samp{i}. |
| 946 | |
| 947 | \item[\samp{l} (integer) {[long int]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 948 | Convert a C \ctype{long int} to a Python integer object. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 949 | |
| 950 | \item[\samp{c} (string of length 1) {[char]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 951 | Convert a C \ctype{int} representing a character to a Python string of |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 952 | length 1. |
| 953 | |
| 954 | \item[\samp{d} (float) {[double]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 955 | Convert a C \ctype{double} to a Python floating point number. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 956 | |
| 957 | \item[\samp{f} (float) {[float]}] |
| 958 | Same as \samp{d}. |
| 959 | |
| 960 | \item[\samp{O} (object) {[PyObject *]}] |
| 961 | Pass a Python object untouched (except for its reference count, which |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 962 | is incremented by one). If the object passed in is a \NULL{} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 963 | pointer, it is assumed that this was caused because the call producing |
| 964 | the argument found an error and set an exception. Therefore, |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 965 | \cfunction{Py_BuildValue()} will return \NULL{} but won't raise an |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 966 | exception. If no exception has been raised yet, |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 967 | \cdata{PyExc_SystemError} is set. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 968 | |
| 969 | \item[\samp{S} (object) {[PyObject *]}] |
| 970 | Same as \samp{O}. |
| 971 | |
Guido van Rossum | d358afe | 1998-12-23 05:02:08 +0000 | [diff] [blame] | 972 | \item[\samp{N} (object) {[PyObject *]}] |
| 973 | Same as \samp{O}, except it doesn't increment the reference count on |
| 974 | the object. Useful when the object is created by a call to an object |
| 975 | constructor in the argument list. |
| 976 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 977 | \item[\samp{O\&} (object) {[\var{converter}, \var{anything}]}] |
| 978 | Convert \var{anything} to a Python object through a \var{converter} |
| 979 | function. The function is called with \var{anything} (which should be |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 980 | compatible with \ctype{void *}) as its argument and should return a |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 981 | ``new'' Python object, or \NULL{} if an error occurred. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 982 | |
| 983 | \item[\samp{(\var{items})} (tuple) {[\var{matching-items}]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 984 | Convert a sequence of C values to a Python tuple with the same number |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 985 | of items. |
| 986 | |
| 987 | \item[\samp{[\var{items}]} (list) {[\var{matching-items}]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 988 | Convert a sequence of C values to a Python list with the same number |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 989 | of items. |
| 990 | |
| 991 | \item[\samp{\{\var{items}\}} (dictionary) {[\var{matching-items}]}] |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 992 | Convert a sequence of C values to a Python dictionary. Each pair of |
| 993 | consecutive C values adds one item to the dictionary, serving as key |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 994 | and value, respectively. |
| 995 | |
| 996 | \end{description} |
| 997 | |
| 998 | If there is an error in the format string, the |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 999 | \cdata{PyExc_SystemError} exception is raised and \NULL{} returned. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1000 | |
| 1001 | 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] | 1002 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1003 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1004 | Py_BuildValue("") None |
| 1005 | Py_BuildValue("i", 123) 123 |
Guido van Rossum | f23e0fe | 1995-03-18 11:04:29 +0000 | [diff] [blame] | 1006 | Py_BuildValue("iii", 123, 456, 789) (123, 456, 789) |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1007 | Py_BuildValue("s", "hello") 'hello' |
| 1008 | Py_BuildValue("ss", "hello", "world") ('hello', 'world') |
| 1009 | Py_BuildValue("s#", "hello", 4) 'hell' |
| 1010 | Py_BuildValue("()") () |
| 1011 | Py_BuildValue("(i)", 123) (123,) |
| 1012 | Py_BuildValue("(ii)", 123, 456) (123, 456) |
| 1013 | Py_BuildValue("(i,i)", 123, 456) (123, 456) |
| 1014 | Py_BuildValue("[i,i]", 123, 456) [123, 456] |
Guido van Rossum | f23e0fe | 1995-03-18 11:04:29 +0000 | [diff] [blame] | 1015 | Py_BuildValue("{s:i,s:i}", |
| 1016 | "abc", 123, "def", 456) {'abc': 123, 'def': 456} |
| 1017 | Py_BuildValue("((ii)(ii)) (ii)", |
| 1018 | 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6)) |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1019 | \end{verbatim} |
| 1020 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1021 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1022 | \section{Reference Counts |
| 1023 | \label{refcounts}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1024 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1025 | In languages like C or \Cpp{}, the programmer is responsible for |
| 1026 | dynamic allocation and deallocation of memory on the heap. In C, |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1027 | this is done using the functions \cfunction{malloc()} and |
| 1028 | \cfunction{free()}. In \Cpp{}, the operators \keyword{new} and |
| 1029 | \keyword{delete} are used with essentially the same meaning; they are |
| 1030 | actually implemented using \cfunction{malloc()} and |
| 1031 | \cfunction{free()}, so we'll restrict the following discussion to the |
| 1032 | latter. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1033 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1034 | Every block of memory allocated with \cfunction{malloc()} should |
| 1035 | eventually be returned to the pool of available memory by exactly one |
| 1036 | call to \cfunction{free()}. It is important to call |
| 1037 | \cfunction{free()} at the right time. If a block's address is |
| 1038 | forgotten but \cfunction{free()} is not called for it, the memory it |
| 1039 | occupies cannot be reused until the program terminates. This is |
| 1040 | called a \dfn{memory leak}. On the other hand, if a program calls |
| 1041 | \cfunction{free()} for a block and then continues to use the block, it |
| 1042 | creates a conflict with re-use of the block through another |
| 1043 | \cfunction{malloc()} call. This is called \dfn{using freed memory}. |
| 1044 | It has the same bad consequences as referencing uninitialized data --- |
| 1045 | core dumps, wrong results, mysterious crashes. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1046 | |
| 1047 | Common causes of memory leaks are unusual paths through the code. For |
| 1048 | instance, a function may allocate a block of memory, do some |
| 1049 | calculation, and then free the block again. Now a change in the |
| 1050 | requirements for the function may add a test to the calculation that |
| 1051 | detects an error condition and can return prematurely from the |
| 1052 | function. It's easy to forget to free the allocated memory block when |
| 1053 | taking this premature exit, especially when it is added later to the |
| 1054 | code. Such leaks, once introduced, often go undetected for a long |
| 1055 | time: the error exit is taken only in a small fraction of all calls, |
| 1056 | and most modern machines have plenty of virtual memory, so the leak |
| 1057 | only becomes apparent in a long-running process that uses the leaking |
| 1058 | function frequently. Therefore, it's important to prevent leaks from |
| 1059 | happening by having a coding convention or strategy that minimizes |
| 1060 | this kind of errors. |
| 1061 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1062 | Since Python makes heavy use of \cfunction{malloc()} and |
| 1063 | \cfunction{free()}, it needs a strategy to avoid memory leaks as well |
| 1064 | as the use of freed memory. The chosen method is called |
| 1065 | \dfn{reference counting}. The principle is simple: every object |
| 1066 | contains a counter, which is incremented when a reference to the |
| 1067 | object is stored somewhere, and which is decremented when a reference |
| 1068 | to it is deleted. When the counter reaches zero, the last reference |
| 1069 | to the object has been deleted and the object is freed. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1070 | |
| 1071 | An alternative strategy is called \dfn{automatic garbage collection}. |
| 1072 | (Sometimes, reference counting is also referred to as a garbage |
| 1073 | collection strategy, hence my use of ``automatic'' to distinguish the |
| 1074 | two.) The big advantage of automatic garbage collection is that the |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1075 | user doesn't need to call \cfunction{free()} explicitly. (Another claimed |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1076 | advantage is an improvement in speed or memory usage --- this is no |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1077 | hard fact however.) The disadvantage is that for C, there is no |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1078 | truly portable automatic garbage collector, while reference counting |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1079 | can be implemented portably (as long as the functions \cfunction{malloc()} |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1080 | and \cfunction{free()} are available --- which the C Standard guarantees). |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1081 | Maybe some day a sufficiently portable automatic garbage collector |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1082 | will be available for C. Until then, we'll have to live with |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1083 | reference counts. |
| 1084 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1085 | \subsection{Reference Counting in Python |
| 1086 | \label{refcountsInPython}} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1087 | |
| 1088 | There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)}, |
| 1089 | which handle the incrementing and decrementing of the reference count. |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1090 | \cfunction{Py_DECREF()} also frees the object when the count reaches zero. |
| 1091 | For flexibility, it doesn't call \cfunction{free()} directly --- rather, it |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1092 | makes a call through a function pointer in the object's \dfn{type |
| 1093 | object}. For this purpose (and others), every object also contains a |
| 1094 | pointer to its type object. |
| 1095 | |
| 1096 | The big question now remains: when to use \code{Py_INCREF(x)} and |
| 1097 | \code{Py_DECREF(x)}? Let's first introduce some terms. Nobody |
| 1098 | ``owns'' an object; however, you can \dfn{own a reference} to an |
| 1099 | object. An object's reference count is now defined as the number of |
| 1100 | owned references to it. The owner of a reference is responsible for |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1101 | calling \cfunction{Py_DECREF()} when the reference is no longer |
| 1102 | needed. Ownership of a reference can be transferred. There are three |
| 1103 | ways to dispose of an owned reference: pass it on, store it, or call |
| 1104 | \cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference |
| 1105 | creates a memory leak. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1106 | |
| 1107 | It is also possible to \dfn{borrow}\footnote{The metaphor of |
| 1108 | ``borrowing'' a reference is not completely correct: the owner still |
| 1109 | has a copy of the reference.} a reference to an object. The borrower |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1110 | of a reference should not call \cfunction{Py_DECREF()}. The borrower must |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1111 | not hold on to the object longer than the owner from which it was |
| 1112 | borrowed. Using a borrowed reference after the owner has disposed of |
| 1113 | it risks using freed memory and should be avoided |
| 1114 | completely.\footnote{Checking that the reference count is at least 1 |
| 1115 | \strong{does not work} --- the reference count itself could be in |
| 1116 | freed memory and may thus be reused for another object!} |
| 1117 | |
| 1118 | The advantage of borrowing over owning a reference is that you don't |
| 1119 | need to take care of disposing of the reference on all possible paths |
| 1120 | through the code --- in other words, with a borrowed reference you |
| 1121 | don't run the risk of leaking when a premature exit is taken. The |
| 1122 | disadvantage of borrowing over leaking is that there are some subtle |
| 1123 | situations where in seemingly correct code a borrowed reference can be |
| 1124 | used after the owner from which it was borrowed has in fact disposed |
| 1125 | of it. |
| 1126 | |
| 1127 | A borrowed reference can be changed into an owned reference by calling |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1128 | \cfunction{Py_INCREF()}. This does not affect the status of the owner from |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1129 | which the reference was borrowed --- it creates a new owned reference, |
| 1130 | and gives full owner responsibilities (i.e., the new owner must |
| 1131 | dispose of the reference properly, as well as the previous owner). |
| 1132 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1133 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1134 | \subsection{Ownership Rules |
| 1135 | \label{ownershipRules}} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1136 | |
| 1137 | Whenever an object reference is passed into or out of a function, it |
| 1138 | is part of the function's interface specification whether ownership is |
| 1139 | transferred with the reference or not. |
| 1140 | |
| 1141 | Most functions that return a reference to an object pass on ownership |
| 1142 | with the reference. In particular, all functions whose function it is |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1143 | to create a new object, e.g.\ \cfunction{PyInt_FromLong()} and |
| 1144 | \cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if in |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1145 | fact, in some cases, you don't receive a reference to a brand new |
| 1146 | object, you still receive ownership of the reference. For instance, |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1147 | \cfunction{PyInt_FromLong()} maintains a cache of popular values and can |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1148 | return a reference to a cached item. |
| 1149 | |
| 1150 | Many functions that extract objects from other objects also transfer |
| 1151 | ownership with the reference, for instance |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1152 | \cfunction{PyObject_GetAttrString()}. The picture is less clear, here, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1153 | however, since a few common routines are exceptions: |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1154 | \cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()}, |
| 1155 | \cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()} |
| 1156 | all return references that you borrow from the tuple, list or |
| 1157 | dictionary. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1158 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1159 | The function \cfunction{PyImport_AddModule()} also returns a borrowed |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1160 | reference, even though it may actually create the object it returns: |
| 1161 | this is possible because an owned reference to the object is stored in |
| 1162 | \code{sys.modules}. |
| 1163 | |
| 1164 | When you pass an object reference into another function, in general, |
| 1165 | the function borrows the reference from you --- if it needs to store |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1166 | it, it will use \cfunction{Py_INCREF()} to become an independent |
| 1167 | owner. There are exactly two important exceptions to this rule: |
| 1168 | \cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These |
| 1169 | functions take over ownership of the item passed to them --- even if |
| 1170 | they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 1171 | take over ownership --- they are ``normal.'') |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1172 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1173 | When a C function is called from Python, it borrows references to its |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1174 | arguments from the caller. The caller owns a reference to the object, |
| 1175 | so the borrowed reference's lifetime is guaranteed until the function |
| 1176 | returns. Only when such a borrowed reference must be stored or passed |
| 1177 | on, it must be turned into an owned reference by calling |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1178 | \cfunction{Py_INCREF()}. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1179 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1180 | The object reference returned from a C function that is called from |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1181 | Python must be an owned reference --- ownership is tranferred from the |
| 1182 | function to its caller. |
| 1183 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1184 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1185 | \subsection{Thin Ice |
| 1186 | \label{thinIce}} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1187 | |
| 1188 | There are a few situations where seemingly harmless use of a borrowed |
| 1189 | reference can lead to problems. These all have to do with implicit |
| 1190 | invocations of the interpreter, which can cause the owner of a |
| 1191 | reference to dispose of it. |
| 1192 | |
| 1193 | The first and most important case to know about is using |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1194 | \cfunction{Py_DECREF()} on an unrelated object while borrowing a |
| 1195 | reference to a list item. For instance: |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1196 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1197 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1198 | bug(PyObject *list) { |
| 1199 | PyObject *item = PyList_GetItem(list, 0); |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 1200 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1201 | PyList_SetItem(list, 1, PyInt_FromLong(0L)); |
| 1202 | PyObject_Print(item, stdout, 0); /* BUG! */ |
| 1203 | } |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1204 | \end{verbatim} |
| 1205 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1206 | This function first borrows a reference to \code{list[0]}, then |
| 1207 | replaces \code{list[1]} with the value \code{0}, and finally prints |
| 1208 | the borrowed reference. Looks harmless, right? But it's not! |
| 1209 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1210 | Let's follow the control flow into \cfunction{PyList_SetItem()}. The list |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1211 | owns references to all its items, so when item 1 is replaced, it has |
| 1212 | to dispose of the original item 1. Now let's suppose the original |
| 1213 | item 1 was an instance of a user-defined class, and let's further |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1214 | suppose that the class defined a \method{__del__()} method. If this |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1215 | class instance has a reference count of 1, disposing of it will call |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1216 | its \method{__del__()} method. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1217 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1218 | Since it is written in Python, the \method{__del__()} method can execute |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1219 | arbitrary Python code. Could it perhaps do something to invalidate |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1220 | the reference to \code{item} in \cfunction{bug()}? You bet! Assuming |
| 1221 | that the list passed into \cfunction{bug()} is accessible to the |
| 1222 | \method{__del__()} method, it could execute a statement to the effect of |
| 1223 | \samp{del list[0]}, and assuming this was the last reference to that |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1224 | object, it would free the memory associated with it, thereby |
| 1225 | invalidating \code{item}. |
| 1226 | |
| 1227 | The solution, once you know the source of the problem, is easy: |
| 1228 | temporarily increment the reference count. The correct version of the |
| 1229 | function reads: |
| 1230 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1231 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1232 | no_bug(PyObject *list) { |
| 1233 | PyObject *item = PyList_GetItem(list, 0); |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 1234 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1235 | Py_INCREF(item); |
| 1236 | PyList_SetItem(list, 1, PyInt_FromLong(0L)); |
| 1237 | PyObject_Print(item, stdout, 0); |
| 1238 | Py_DECREF(item); |
| 1239 | } |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1240 | \end{verbatim} |
| 1241 | |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1242 | This is a true story. An older version of Python contained variants |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1243 | of this bug and someone spent a considerable amount of time in a C |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1244 | debugger to figure out why his \method{__del__()} methods would fail... |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1245 | |
| 1246 | The second case of problems with a borrowed reference is a variant |
| 1247 | involving threads. Normally, multiple threads in the Python |
| 1248 | interpreter can't get in each other's way, because there is a global |
| 1249 | lock protecting Python's entire object space. However, it is possible |
| 1250 | to temporarily release this lock using the macro |
| 1251 | \code{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using |
| 1252 | \code{Py_END_ALLOW_THREADS}. This is common around blocking I/O |
| 1253 | calls, to let other threads use the CPU while waiting for the I/O to |
| 1254 | complete. Obviously, the following function has the same problem as |
| 1255 | the previous one: |
| 1256 | |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1257 | \begin{verbatim} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1258 | bug(PyObject *list) { |
| 1259 | PyObject *item = PyList_GetItem(list, 0); |
| 1260 | Py_BEGIN_ALLOW_THREADS |
| 1261 | ...some blocking I/O call... |
| 1262 | Py_END_ALLOW_THREADS |
| 1263 | PyObject_Print(item, stdout, 0); /* BUG! */ |
| 1264 | } |
Fred Drake | 1e11a5c | 1998-02-13 07:11:32 +0000 | [diff] [blame] | 1265 | \end{verbatim} |
| 1266 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1267 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1268 | \subsection{NULL Pointers |
| 1269 | \label{nullPointers}} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1270 | |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 1271 | In general, functions that take object references as arguments do not |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1272 | expect you to pass them \NULL{} pointers, and will dump core (or |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1273 | cause later core dumps) if you do so. Functions that return object |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1274 | references generally return \NULL{} only to indicate that an |
| 1275 | exception occurred. The reason for not testing for \NULL{} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1276 | arguments is that functions often pass the objects they receive on to |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1277 | other function --- if each function were to test for \NULL{}, |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1278 | there would be a lot of redundant tests and the code would run slower. |
| 1279 | |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1280 | It is better to test for \NULL{} only at the ``source'', i.e.\ when a |
| 1281 | pointer that may be \NULL{} is received, e.g.\ from |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1282 | \cfunction{malloc()} or from a function that may raise an exception. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1283 | |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1284 | The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()} |
Fred Drake | a0dbddf | 1998-04-02 06:50:02 +0000 | [diff] [blame] | 1285 | do not check for \NULL{} pointers --- however, their variants |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1286 | \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do. |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1287 | |
| 1288 | The macros for checking for a particular object type |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1289 | (\code{Py\var{type}_Check()}) don't check for \NULL{} pointers --- |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1290 | again, there is much code that calls several of these in a row to test |
| 1291 | an object against various different expected types, and this would |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1292 | generate redundant tests. There are no variants with \NULL{} |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1293 | checking. |
| 1294 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1295 | The C function calling mechanism guarantees that the argument list |
| 1296 | passed to C functions (\code{args} in the examples) is never |
Fred Drake | 52e2d51 | 1999-04-05 21:26:37 +0000 | [diff] [blame] | 1297 | \NULL{} --- in fact it guarantees that it is always a tuple.\footnote{ |
| 1298 | These guarantees don't hold when you use the ``old'' style |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1299 | calling convention --- this is still found in much existing code.} |
| 1300 | |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1301 | It is a severe error to ever let a \NULL{} pointer ``escape'' to |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1302 | the Python user. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1303 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1304 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1305 | \section{Writing Extensions in \Cpp{} |
| 1306 | \label{cplusplus}} |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1307 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1308 | It is possible to write extension modules in \Cpp{}. Some restrictions |
Guido van Rossum | ed39cd0 | 1995-10-08 00:17:19 +0000 | [diff] [blame] | 1309 | apply. If the main program (the Python interpreter) is compiled and |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1310 | linked by the C compiler, global or static objects with constructors |
Guido van Rossum | ed39cd0 | 1995-10-08 00:17:19 +0000 | [diff] [blame] | 1311 | cannot be used. This is not a problem if the main program is linked |
Guido van Rossum | afcd589 | 1998-02-05 19:59:39 +0000 | [diff] [blame] | 1312 | by the \Cpp{} compiler. Functions that will be called by the |
| 1313 | Python interpreter (in particular, module initalization functions) |
| 1314 | have to be declared using \code{extern "C"}. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1315 | It is unnecessary to enclose the Python header files in |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1316 | \code{extern "C" \{...\}} --- they use this form already if the symbol |
Fred Drake | 0fd8268 | 1998-01-09 05:39:38 +0000 | [diff] [blame] | 1317 | \samp{__cplusplus} is defined (all recent \Cpp{} compilers define this |
Guido van Rossum | 5049bcb | 1995-03-13 16:55:23 +0000 | [diff] [blame] | 1318 | symbol). |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1319 | |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1320 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1321 | \section{Providing a C API for an Extension Module |
| 1322 | \label{using-cobjects}} |
| 1323 | \sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1324 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1325 | Many extension modules just provide new functions and types to be |
| 1326 | used from Python, but sometimes the code in an extension module can |
| 1327 | be useful for other extension modules. For example, an extension |
| 1328 | module could implement a type ``collection'' which works like lists |
| 1329 | without order. Just like the standard Python list type has a C API |
| 1330 | which permits extension modules to create and manipulate lists, this |
| 1331 | new collection type should have a set of C functions for direct |
| 1332 | manipulation from other extension modules. |
| 1333 | |
| 1334 | At first sight this seems easy: just write the functions (without |
| 1335 | declaring them \keyword{static}, of course), provide an appropriate |
| 1336 | header file, and document the C API. And in fact this would work if |
| 1337 | all extension modules were always linked statically with the Python |
| 1338 | interpreter. When modules are used as shared libraries, however, the |
| 1339 | symbols defined in one module may not be visible to another module. |
| 1340 | The details of visibility depend on the operating system; some systems |
| 1341 | use one global namespace for the Python interpreter and all extension |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1342 | modules (e.g.\ Windows), whereas others require an explicit list of |
| 1343 | imported symbols at module link time (e.g.\ AIX), or offer a choice of |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1344 | different strategies (most Unices). And even if symbols are globally |
| 1345 | visible, the module whose functions one wishes to call might not have |
| 1346 | been loaded yet! |
| 1347 | |
| 1348 | Portability therefore requires not to make any assumptions about |
| 1349 | symbol visibility. This means that all symbols in extension modules |
| 1350 | should be declared \keyword{static}, except for the module's |
| 1351 | initialization function, in order to avoid name clashes with other |
| 1352 | extension modules (as discussed in section~\ref{methodTable}). And it |
| 1353 | means that symbols that \emph{should} be accessible from other |
| 1354 | extension modules must be exported in a different way. |
| 1355 | |
| 1356 | Python provides a special mechanism to pass C-level information (i.e. |
| 1357 | pointers) from one extension module to another one: CObjects. |
| 1358 | A CObject is a Python data type which stores a pointer (\ctype{void |
| 1359 | *}). CObjects can only be created and accessed via their C API, but |
| 1360 | they can be passed around like any other Python object. In particular, |
| 1361 | they can be assigned to a name in an extension module's namespace. |
| 1362 | Other extension modules can then import this module, retrieve the |
| 1363 | value of this name, and then retrieve the pointer from the CObject. |
| 1364 | |
| 1365 | There are many ways in which CObjects can be used to export the C API |
| 1366 | of an extension module. Each name could get its own CObject, or all C |
| 1367 | API pointers could be stored in an array whose address is published in |
| 1368 | a CObject. And the various tasks of storing and retrieving the pointers |
| 1369 | can be distributed in different ways between the module providing the |
| 1370 | code and the client modules. |
| 1371 | |
| 1372 | The following example demonstrates an approach that puts most of the |
| 1373 | burden on the writer of the exporting module, which is appropriate |
| 1374 | for commonly used library modules. It stores all C API pointers |
| 1375 | (just one in the example!) in an array of \ctype{void} pointers which |
| 1376 | becomes the value of a CObject. The header file corresponding to |
| 1377 | the module provides a macro that takes care of importing the module |
| 1378 | and retrieving its C API pointers; client modules only have to call |
| 1379 | this macro before accessing the C API. |
| 1380 | |
| 1381 | The exporting module is a modification of the \module{spam} module from |
| 1382 | section~\ref{simpleExample}. The function \function{spam.system()} |
| 1383 | does not call the C library function \cfunction{system()} directly, |
| 1384 | but a function \cfunction{PySpam_System()}, which would of course do |
| 1385 | something more complicated in reality (such as adding ``spam'' to |
| 1386 | every command). This function \cfunction{PySpam_System()} is also |
| 1387 | exported to other extension modules. |
| 1388 | |
| 1389 | The function \cfunction{PySpam_System()} is a plain C function, |
| 1390 | declared \keyword{static} like everything else: |
| 1391 | |
| 1392 | \begin{verbatim} |
| 1393 | static int |
| 1394 | PySpam_System(command) |
| 1395 | char *command; |
| 1396 | { |
| 1397 | return system(command); |
| 1398 | } |
| 1399 | \end{verbatim} |
| 1400 | |
| 1401 | The function \cfunction{spam_system()} is modified in a trivial way: |
| 1402 | |
| 1403 | \begin{verbatim} |
| 1404 | static PyObject * |
| 1405 | spam_system(self, args) |
| 1406 | PyObject *self; |
| 1407 | PyObject *args; |
| 1408 | { |
| 1409 | char *command; |
| 1410 | int sts; |
| 1411 | |
| 1412 | if (!PyArg_ParseTuple(args, "s", &command)) |
| 1413 | return NULL; |
| 1414 | sts = PySpam_System(command); |
| 1415 | return Py_BuildValue("i", sts); |
| 1416 | } |
| 1417 | \end{verbatim} |
| 1418 | |
| 1419 | In the beginning of the module, right after the line |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1420 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1421 | \begin{verbatim} |
| 1422 | #include "Python.h" |
| 1423 | \end{verbatim} |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1424 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1425 | two more lines must be added: |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1426 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1427 | \begin{verbatim} |
| 1428 | #define SPAM_MODULE |
| 1429 | #include "spammodule.h" |
| 1430 | \end{verbatim} |
| 1431 | |
| 1432 | The \code{\#define} is used to tell the header file that it is being |
| 1433 | included in the exporting module, not a client module. Finally, |
| 1434 | the module's initialization function must take care of initializing |
| 1435 | the C API pointer array: |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1436 | |
Fred Drake | ec9fbe9 | 1999-02-15 16:20:25 +0000 | [diff] [blame] | 1437 | \begin{verbatim} |
| 1438 | void |
| 1439 | initspam() |
| 1440 | { |
| 1441 | PyObject *m, *d; |
| 1442 | static void *PySpam_API[PySpam_API_pointers]; |
| 1443 | PyObject *c_api_object; |
| 1444 | m = Py_InitModule("spam", SpamMethods); |
| 1445 | |
| 1446 | /* Initialize the C API pointer array */ |
| 1447 | PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; |
| 1448 | |
| 1449 | /* Create a CObject containing the API pointer array's address */ |
| 1450 | c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL); |
| 1451 | |
| 1452 | /* Create a name for this object in the module's namespace */ |
| 1453 | d = PyModule_GetDict(m); |
| 1454 | PyDict_SetItemString(d, "_C_API", c_api_object); |
| 1455 | } |
| 1456 | \end{verbatim} |
| 1457 | |
| 1458 | Note that \code{PySpam_API} is declared \code{static}; otherwise |
| 1459 | the pointer array would disappear when \code{initspam} terminates! |
| 1460 | |
| 1461 | The bulk of the work is in the header file \file{spammodule.h}, |
| 1462 | which looks like this: |
| 1463 | |
| 1464 | \begin{verbatim} |
| 1465 | #ifndef Py_SPAMMODULE_H |
| 1466 | #define Py_SPAMMODULE_H |
| 1467 | #ifdef __cplusplus |
| 1468 | extern "C" { |
| 1469 | #endif |
| 1470 | |
| 1471 | /* Header file for spammodule */ |
| 1472 | |
| 1473 | /* C API functions */ |
| 1474 | #define PySpam_System_NUM 0 |
| 1475 | #define PySpam_System_RETURN int |
| 1476 | #define PySpam_System_PROTO Py_PROTO((char *command)) |
| 1477 | |
| 1478 | /* Total number of C API pointers */ |
| 1479 | #define PySpam_API_pointers 1 |
| 1480 | |
| 1481 | |
| 1482 | #ifdef SPAM_MODULE |
| 1483 | /* This section is used when compiling spammodule.c */ |
| 1484 | |
| 1485 | static PySpam_System_RETURN PySpam_System PySpam_System_PROTO; |
| 1486 | |
| 1487 | #else |
| 1488 | /* This section is used in modules that use spammodule's API */ |
| 1489 | |
| 1490 | static void **PySpam_API; |
| 1491 | |
| 1492 | #define PySpam_System \ |
| 1493 | (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM]) |
| 1494 | |
| 1495 | #define import_spam() \ |
| 1496 | { \ |
| 1497 | PyObject *module = PyImport_ImportModule("spam"); \ |
| 1498 | if (module != NULL) { \ |
| 1499 | PyObject *module_dict = PyModule_GetDict(module); \ |
| 1500 | PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \ |
| 1501 | if (PyCObject_Check(c_api_object)) { \ |
| 1502 | PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); \ |
| 1503 | } \ |
| 1504 | } \ |
| 1505 | } |
| 1506 | |
| 1507 | #endif |
| 1508 | |
| 1509 | #ifdef __cplusplus |
| 1510 | } |
| 1511 | #endif |
| 1512 | |
| 1513 | #endif /* !defined(Py_SPAMMODULE_H */ |
| 1514 | \end{verbatim} |
| 1515 | |
| 1516 | All that a client module must do in order to have access to the |
| 1517 | function \cfunction{PySpam_System()} is to call the function (or |
| 1518 | rather macro) \cfunction{import_spam()} in its initialization |
| 1519 | function: |
| 1520 | |
| 1521 | \begin{verbatim} |
| 1522 | void |
| 1523 | initclient() |
| 1524 | { |
| 1525 | PyObject *m; |
| 1526 | |
| 1527 | Py_InitModule("client", ClientMethods); |
| 1528 | import_spam(); |
| 1529 | } |
| 1530 | \end{verbatim} |
| 1531 | |
| 1532 | The main disadvantage of this approach is that the file |
| 1533 | \file{spammodule.h} is rather complicated. However, the |
| 1534 | basic structure is the same for each function that is |
| 1535 | exported, so it has to be learned only once. |
| 1536 | |
| 1537 | Finally it should be mentioned that CObjects offer additional |
| 1538 | functionality, which is especially useful for memory allocation and |
| 1539 | deallocation of the pointer stored in a CObject. The details |
| 1540 | are described in the \emph{Python/C API Reference Manual} in the |
| 1541 | section ``CObjects'' and in the implementation of CObjects (files |
| 1542 | \file{Include/cobject.h} and \file{Objects/cobject.c} in the |
| 1543 | Python source code distribution). |
| 1544 | |
| 1545 | |
| 1546 | \chapter{Building C and \Cpp{} Extensions on \UNIX{} |
Fred Drake | 3de61bc | 1999-02-16 21:14:16 +0000 | [diff] [blame] | 1547 | \label{building-on-unix}} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1548 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1549 | \sectionauthor{Jim Fulton}{jim@Digicool.com} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1550 | |
| 1551 | |
| 1552 | %The make file make file, building C extensions on Unix |
| 1553 | |
| 1554 | |
| 1555 | Starting in Python 1.4, Python provides a special make file for |
| 1556 | building make files for building dynamically-linked extensions and |
| 1557 | custom interpreters. The make file make file builds a make file |
| 1558 | that reflects various system variables determined by configure when |
| 1559 | the Python interpreter was built, so people building module's don't |
| 1560 | have to resupply these settings. This vastly simplifies the process |
| 1561 | of building extensions and custom interpreters on Unix systems. |
| 1562 | |
| 1563 | The make file make file is distributed as the file |
| 1564 | \file{Misc/Makefile.pre.in} in the Python source distribution. The |
| 1565 | first step in building extensions or custom interpreters is to copy |
| 1566 | this make file to a development directory containing extension module |
| 1567 | source. |
| 1568 | |
| 1569 | The make file make file, \file{Makefile.pre.in} uses metadata |
| 1570 | provided in a file named \file{Setup}. The format of the \file{Setup} |
| 1571 | file is the same as the \file{Setup} (or \file{Setup.in}) file |
| 1572 | provided in the \file{Modules/} directory of the Python source |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1573 | distribution. The \file{Setup} file contains variable definitions: |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1574 | |
| 1575 | \begin{verbatim} |
| 1576 | EC=/projects/ExtensionClass |
| 1577 | \end{verbatim} |
| 1578 | |
| 1579 | and module description lines. It can also contain blank lines and |
| 1580 | comment lines that start with \character{\#}. |
| 1581 | |
| 1582 | A module description line includes a module name, source files, |
| 1583 | options, variable references, and other input files, such |
| 1584 | as libraries or object files. Consider a simple example:: |
| 1585 | |
| 1586 | \begin{verbatim} |
| 1587 | ExtensionClass ExtensionClass.c |
| 1588 | \end{verbatim} |
| 1589 | |
| 1590 | This is the simplest form of a module definition line. It defines a |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1591 | module, \module{ExtensionClass}, which has a single source file, |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1592 | \file{ExtensionClass.c}. |
| 1593 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1594 | This slightly more complex example uses an \strong{-I} option to |
| 1595 | specify an include directory: |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1596 | |
| 1597 | \begin{verbatim} |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1598 | EC=/projects/ExtensionClass |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1599 | cPersistence cPersistence.c -I$(EC) |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1600 | \end{verbatim} % $ <-- bow to font lock |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1601 | |
| 1602 | This example also illustrates the format for variable references. |
| 1603 | |
| 1604 | For systems that support dynamic linking, the \file{Setup} file should |
| 1605 | begin: |
| 1606 | |
| 1607 | \begin{verbatim} |
| 1608 | *shared* |
| 1609 | \end{verbatim} |
| 1610 | |
| 1611 | to indicate that the modules defined in \file{Setup} are to be built |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 1612 | as dynamically linked modules. A line containing only \samp{*static*} |
| 1613 | can be used to indicate the subsequently listed modules should be |
| 1614 | statically linked. |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1615 | |
| 1616 | Here is a complete \file{Setup} file for building a |
| 1617 | \module{cPersistent} module: |
| 1618 | |
| 1619 | \begin{verbatim} |
| 1620 | # Set-up file to build the cPersistence module. |
| 1621 | # Note that the text should begin in the first column. |
| 1622 | *shared* |
| 1623 | |
| 1624 | # We need the path to the directory containing the ExtensionClass |
| 1625 | # include file. |
| 1626 | EC=/projects/ExtensionClass |
| 1627 | cPersistence cPersistence.c -I$(EC) |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1628 | \end{verbatim} % $ <-- bow to font lock |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1629 | |
| 1630 | After the \file{Setup} file has been created, \file{Makefile.pre.in} |
| 1631 | is run with the \samp{boot} target to create a make file: |
| 1632 | |
| 1633 | \begin{verbatim} |
| 1634 | make -f Makefile.pre.in boot |
| 1635 | \end{verbatim} |
| 1636 | |
| 1637 | This creates the file, Makefile. To build the extensions, simply |
| 1638 | run the created make file: |
| 1639 | |
| 1640 | \begin{verbatim} |
| 1641 | make |
| 1642 | \end{verbatim} |
| 1643 | |
| 1644 | It's not necessary to re-run \file{Makefile.pre.in} if the |
| 1645 | \file{Setup} file is changed. The make file automatically rebuilds |
| 1646 | itself if the \file{Setup} file changes. |
| 1647 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1648 | |
| 1649 | \section{Building Custom Interpreters \label{custom-interps}} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1650 | |
| 1651 | The make file built by \file{Makefile.pre.in} can be run with the |
| 1652 | \samp{static} target to build an interpreter: |
| 1653 | |
| 1654 | \begin{verbatim} |
| 1655 | make static |
| 1656 | \end{verbatim} |
| 1657 | |
| 1658 | Any modules defined in the Setup file before the \samp{*shared*} line |
| 1659 | will be statically linked into the interpreter. Typically, a |
| 1660 | \samp{*shared*} line is omitted from the Setup file when a custom |
| 1661 | interpreter is desired. |
| 1662 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1663 | |
| 1664 | \section{Module Definition Options \label{module-defn-options}} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1665 | |
| 1666 | Several compiler options are supported: |
| 1667 | |
| 1668 | \begin{tableii}{l|l}{}{Option}{Meaning} |
| 1669 | \lineii{-C}{Tell the C pre-processor not to discard comments} |
| 1670 | \lineii{-D\var{name}=\var{value}}{Define a macro} |
| 1671 | \lineii{-I\var{dir}}{Specify an include directory, \var{dir}} |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1672 | \lineii{-L\var{dir}}{Specify a link-time library directory, \var{dir}} |
| 1673 | \lineii{-R\var{dir}}{Specify a run-time library directory, \var{dir}} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1674 | \lineii{-l\var{lib}}{Link a library, \var{lib}} |
| 1675 | \lineii{-U\var{name}}{Undefine a macro} |
| 1676 | \end{tableii} |
| 1677 | |
| 1678 | Other compiler options can be included (snuck in) by putting them |
Fred Drake | dc12ec8 | 1999-03-09 18:36:55 +0000 | [diff] [blame] | 1679 | in variables. |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1680 | |
| 1681 | Source files can include files with \file{.c}, \file{.C}, \file{.cc}, |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1682 | \file{.cpp}, \file{.cxx}, and \file{.c++} extensions. |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1683 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1684 | Other input files include files with \file{.a}, \file{.o}, \file{.sl}, |
| 1685 | and \file{.so} extensions. |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1686 | |
| 1687 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1688 | \section{Example \label{module-defn-example}} |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1689 | |
| 1690 | Here is a more complicated example from \file{Modules/Setup.in}: |
| 1691 | |
| 1692 | \begin{verbatim} |
| 1693 | GMP=/ufs/guido/src/gmp |
| 1694 | mpz mpzmodule.c -I$(GMP) $(GMP)/libgmp.a |
| 1695 | \end{verbatim} |
| 1696 | |
| 1697 | which could also be written as: |
| 1698 | |
| 1699 | \begin{verbatim} |
| 1700 | mpz mpzmodule.c -I$(GMP) -L$(GMP) -lgmp |
| 1701 | \end{verbatim} |
| 1702 | |
| 1703 | |
| 1704 | \section{Distributing your extension modules |
| 1705 | \label{distributing}} |
| 1706 | |
| 1707 | When distributing your extension modules in source form, make sure to |
| 1708 | include a \file{Setup} file. The \file{Setup} file should be named |
| 1709 | \file{Setup.in} in the distribution. The make file make file, |
| 1710 | \file{Makefile.pre.in}, will copy \file{Setup.in} to \file{Setup}. |
| 1711 | Distributing a \file{Setup.in} file makes it easy for people to |
| 1712 | customize the \file{Setup} file while keeping the original in |
| 1713 | \file{Setup.in}. |
| 1714 | |
| 1715 | It is a good idea to include a copy of \file{Makefile.pre.in} for |
| 1716 | people who do not have a source distribution of Python. |
| 1717 | |
| 1718 | Do not distribute a make file. People building your modules |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1719 | should use \file{Makefile.pre.in} to build their own make file. A |
| 1720 | \file{README} file included in the package should provide simple |
| 1721 | instructions to perform the build. |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1722 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1723 | Work is being done to make building and installing Python extensions |
| 1724 | easier for all platforms; this work in likely to supplant the current |
| 1725 | approach at some point in the future. For more information or to |
| 1726 | participate in the effort, refer to |
| 1727 | \url{http://www.python.org/sigs/distutils-sig/} on the Python Web |
| 1728 | site. |
| 1729 | |
Fred Drake | e743fd0 | 1998-11-24 17:07:29 +0000 | [diff] [blame] | 1730 | |
Fred Drake | 3de61bc | 1999-02-16 21:14:16 +0000 | [diff] [blame] | 1731 | \chapter{Building C and \Cpp{} Extensions on Windows |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1732 | \label{building-on-windows}} |
Fred Drake | 3de61bc | 1999-02-16 21:14:16 +0000 | [diff] [blame] | 1733 | |
| 1734 | |
| 1735 | This chapter briefly explains how to create a Windows extension module |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1736 | for Python using Microsoft Visual \Cpp{}, and follows with more |
| 1737 | detailed background information on how it works. The explanatory |
| 1738 | material is useful for both the Windows programmer learning to build |
| 1739 | Python extensions and the \UNIX{} programming interested in producing |
| 1740 | software which can be successfully built on both \UNIX{} and Windows. |
| 1741 | |
Fred Drake | 8e01517 | 1999-02-17 18:12:14 +0000 | [diff] [blame] | 1742 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1743 | \section{A Cookbook Approach \label{win-cookbook}} |
| 1744 | |
| 1745 | \sectionauthor{Neil Schemenauer}{neil_schemenauer@transcanada.com} |
| 1746 | |
| 1747 | This section provides a recipe for building a Python extension on |
| 1748 | Windows. |
Fred Drake | 3de61bc | 1999-02-16 21:14:16 +0000 | [diff] [blame] | 1749 | |
| 1750 | Grab the binary installer from \url{http://www.python.org/} and |
| 1751 | install Python. The binary installer has all of the required header |
| 1752 | files except for \file{config.h}. |
| 1753 | |
| 1754 | Get the source distribution and extract it into a convenient location. |
| 1755 | Copy the \file{config.h} from the \file{PC/} directory into the |
| 1756 | \file{include/} directory created by the installer. |
| 1757 | |
| 1758 | Create a \file{Setup} file for your extension module, as described in |
| 1759 | Chapter \ref{building-on-unix}. |
| 1760 | |
| 1761 | Get David Ascher's \file{compile.py} script from |
Fred Drake | c0fcbc1 | 1999-04-29 02:30:04 +0000 | [diff] [blame] | 1762 | \url{http://starship.python.net/crew/da/compile/}. Run the script to |
Fred Drake | 3de61bc | 1999-02-16 21:14:16 +0000 | [diff] [blame] | 1763 | create Microsoft Visual \Cpp{} project files. |
| 1764 | |
| 1765 | Open the DSW file in V\Cpp{} and select \strong{Build}. |
| 1766 | |
| 1767 | If your module creates a new type, you may have trouble with this line: |
| 1768 | |
| 1769 | \begin{verbatim} |
| 1770 | PyObject_HEAD_INIT(&PyType_Type) |
| 1771 | \end{verbatim} |
| 1772 | |
| 1773 | Change it to: |
| 1774 | |
| 1775 | \begin{verbatim} |
| 1776 | PyObject_HEAD_INIT(NULL) |
| 1777 | \end{verbatim} |
| 1778 | |
| 1779 | and add the following to the module initialization function: |
| 1780 | |
| 1781 | \begin{verbatim} |
| 1782 | MyObject_Type.ob_type = &PyType_Type; |
| 1783 | \end{verbatim} |
| 1784 | |
| 1785 | Refer to section 3 of the Python FAQ |
| 1786 | (\url{http://www.python.org/doc/FAQ.html}) for details on why you must |
| 1787 | do this. |
| 1788 | |
| 1789 | |
Fred Drake | 33698f8 | 1999-02-16 23:06:32 +0000 | [diff] [blame] | 1790 | \section{Differences Between \UNIX{} and Windows |
| 1791 | \label{dynamic-linking}} |
| 1792 | \sectionauthor{Chris Phoenix}{cphoenix@best.com} |
| 1793 | |
| 1794 | |
| 1795 | \UNIX{} and Windows use completely different paradigms for run-time |
| 1796 | loading of code. Before you try to build a module that can be |
| 1797 | dynamically loaded, be aware of how your system works. |
| 1798 | |
| 1799 | In \UNIX{}, a shared object (.so) file contains code to be used by the |
| 1800 | program, and also the names of functions and data that it expects to |
| 1801 | find in the program. When the file is joined to the program, all |
| 1802 | references to those functions and data in the file's code are changed |
| 1803 | to point to the actual locations in the program where the functions |
| 1804 | and data are placed in memory. This is basically a link operation. |
| 1805 | |
| 1806 | In Windows, a dynamic-link library (\file{.dll}) file has no dangling |
| 1807 | references. Instead, an access to functions or data goes through a |
| 1808 | lookup table. So the DLL code does not have to be fixed up at runtime |
| 1809 | to refer to the program's memory; instead, the code already uses the |
| 1810 | DLL's lookup table, and the lookup table is modified at runtime to |
| 1811 | point to the functions and data. |
| 1812 | |
| 1813 | In \UNIX{}, there is only one type of library file (\file{.a}) which |
| 1814 | contains code from several object files (\file{.o}). During the link |
| 1815 | step to create a shared object file (\file{.so}), the linker may find |
| 1816 | that it doesn't know where an identifier is defined. The linker will |
| 1817 | look for it in the object files in the libraries; if it finds it, it |
| 1818 | will include all the code from that object file. |
| 1819 | |
| 1820 | In Windows, there are two types of library, a static library and an |
| 1821 | import library (both called \file{.lib}). A static library is like a |
| 1822 | \UNIX{} \file{.a} file; it contains code to be included as necessary. |
| 1823 | An import library is basically used only to reassure the linker that a |
| 1824 | certain identifier is legal, and will be present in the program when |
| 1825 | the DLL is loaded. So the linker uses the information from the |
| 1826 | import library to build the lookup table for using identifiers that |
| 1827 | are not included in the DLL. When an application or a DLL is linked, |
| 1828 | an import library may be generated, which will need to be used for all |
| 1829 | future DLLs that depend on the symbols in the application or DLL. |
| 1830 | |
| 1831 | Suppose you are building two dynamic-load modules, B and C, which should |
| 1832 | share another block of code A. On \UNIX{}, you would \emph{not} pass |
| 1833 | \file{A.a} to the linker for \file{B.so} and \file{C.so}; that would |
| 1834 | cause it to be included twice, so that B and C would each have their |
| 1835 | own copy. In Windows, building \file{A.dll} will also build |
| 1836 | \file{A.lib}. You \emph{do} pass \file{A.lib} to the linker for B and |
| 1837 | C. \file{A.lib} does not contain code; it just contains information |
| 1838 | which will be used at runtime to access A's code. |
| 1839 | |
| 1840 | In Windows, using an import library is sort of like using \samp{import |
| 1841 | spam}; it gives you access to spam's names, but does not create a |
| 1842 | separate copy. On \UNIX{}, linking with a library is more like |
| 1843 | \samp{from spam import *}; it does create a separate copy. |
| 1844 | |
| 1845 | |
| 1846 | \section{Using DLLs in Practice \label{win-dlls}} |
| 1847 | \sectionauthor{Chris Phoenix}{cphoenix@best.com} |
| 1848 | |
| 1849 | Windows Python is built in Microsoft Visual \Cpp{}; using other |
| 1850 | compilers may or may not work (though Borland seems to). The rest of |
| 1851 | this section is MSV\Cpp{} specific. |
| 1852 | |
| 1853 | When creating DLLs in Windows, you must pass \file{python15.lib} to |
| 1854 | the linker. To build two DLLs, spam and ni (which uses C functions |
| 1855 | found in spam), you could use these commands: |
| 1856 | |
| 1857 | \begin{verbatim} |
| 1858 | cl /LD /I/python/include spam.c ../libs/python15.lib |
| 1859 | cl /LD /I/python/include ni.c spam.lib ../libs/python15.lib |
| 1860 | \end{verbatim} |
| 1861 | |
| 1862 | The first command created three files: \file{spam.obj}, |
| 1863 | \file{spam.dll} and \file{spam.lib}. \file{Spam.dll} does not contain |
| 1864 | any Python functions (such as \cfunction{PyArg_ParseTuple()}), but it |
| 1865 | does know how to find the Python code thanks to \file{python15.lib}. |
| 1866 | |
| 1867 | The second command created \file{ni.dll} (and \file{.obj} and |
| 1868 | \file{.lib}), which knows how to find the necessary functions from |
| 1869 | spam, and also from the Python executable. |
| 1870 | |
| 1871 | Not every identifier is exported to the lookup table. If you want any |
| 1872 | other modules (including Python) to be able to see your identifiers, |
| 1873 | you have to say \samp{_declspec(dllexport)}, as in \samp{void |
| 1874 | _declspec(dllexport) initspam(void)} or \samp{PyObject |
| 1875 | _declspec(dllexport) *NiGetSpamData(void)}. |
| 1876 | |
| 1877 | Developer Studio will throw in a lot of import libraries that you do |
| 1878 | not really need, adding about 100K to your executable. To get rid of |
| 1879 | them, use the Project Settings dialog, Link tab, to specify |
| 1880 | \emph{ignore default libraries}. Add the correct |
| 1881 | \file{msvcrt\var{xx}.lib} to the list of libraries. |
| 1882 | |
| 1883 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1884 | \chapter{Embedding Python in Another Application |
| 1885 | \label{embedding}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1886 | |
| 1887 | Embedding Python is similar to extending it, but not quite. The |
| 1888 | 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] | 1889 | application is still the Python interpreter, while if you embed |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1890 | Python, the main program may have nothing to do with Python --- |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1891 | instead, some parts of the application occasionally call the Python |
| 1892 | interpreter to run some Python code. |
| 1893 | |
| 1894 | So if you are embedding Python, you are providing your own main |
| 1895 | program. One of the things this main program has to do is initialize |
| 1896 | the Python interpreter. At the very least, you have to call the |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1897 | function \cfunction{Py_Initialize()}. There are optional calls to |
| 1898 | pass command line arguments to Python. Then later you can call the |
| 1899 | interpreter from any part of the application. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1900 | |
| 1901 | There are several different ways to call the interpreter: you can pass |
Fred Drake | d7bb303 | 1998-03-03 17:52:07 +0000 | [diff] [blame] | 1902 | a string containing Python statements to |
| 1903 | \cfunction{PyRun_SimpleString()}, or you can pass a stdio file pointer |
| 1904 | and a file name (for identification in error messages only) to |
| 1905 | \cfunction{PyRun_SimpleFile()}. You can also call the lower-level |
| 1906 | operations described in the previous chapters to construct and use |
| 1907 | Python objects. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1908 | |
| 1909 | A simple demo of embedding Python can be found in the directory |
Fred Drake | 295fb43 | 1999-02-16 17:29:42 +0000 | [diff] [blame] | 1910 | \file{Demo/embed/} of the source distribution. |
Guido van Rossum | db65a6c | 1993-11-05 17:11:16 +0000 | [diff] [blame] | 1911 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1912 | |
Fred Drake | 5e8aa54 | 1998-11-16 18:34:07 +0000 | [diff] [blame] | 1913 | \section{Embedding Python in \Cpp{} |
| 1914 | \label{embeddingInCplusplus}} |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1915 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 1916 | It is also possible to embed Python in a \Cpp{} program; precisely how this |
| 1917 | is done will depend on the details of the \Cpp{} system used; in general you |
| 1918 | will need to write the main program in \Cpp{}, and use the \Cpp{} compiler |
| 1919 | to compile and link your program. There is no need to recompile Python |
| 1920 | itself using \Cpp{}. |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1921 | |
Guido van Rossum | 7a2dba2 | 1993-11-05 14:45:11 +0000 | [diff] [blame] | 1922 | \end{document} |