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