Raymond Hettinger | f350160 | 2003-09-08 19:01:04 +0000 | [diff] [blame] | 1 | \chapter{Extending Python with \C{} or \Cpp{} \label{intro}} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 2 | |
| 3 | |
| 4 | It is quite easy to add new built-in modules to Python, if you know |
| 5 | how to program in C. Such \dfn{extension modules} can do two things |
| 6 | that can't be done directly in Python: they can implement new built-in |
| 7 | object types, and they can call C library functions and system calls. |
| 8 | |
| 9 | To support extensions, the Python API (Application Programmers |
| 10 | Interface) defines a set of functions, macros and variables that |
| 11 | provide access to most aspects of the Python run-time system. The |
| 12 | Python API is incorporated in a C source file by including the header |
| 13 | \code{"Python.h"}. |
| 14 | |
| 15 | The compilation of an extension module depends on its intended use as |
| 16 | well as on your system setup; details are given in later chapters. |
| 17 | |
| 18 | |
| 19 | \section{A Simple Example |
| 20 | \label{simpleExample}} |
| 21 | |
| 22 | Let's create an extension module called \samp{spam} (the favorite food |
| 23 | of Monty Python fans...) and let's say we want to create a Python |
| 24 | interface to the C library function \cfunction{system()}.\footnote{An |
| 25 | interface for this function already exists in the standard module |
Raymond Hettinger | 6880431 | 2005-01-01 00:28:46 +0000 | [diff] [blame] | 26 | \module{os} --- it was chosen as a simple and straightforward example.} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 27 | This function takes a null-terminated character string as argument and |
| 28 | returns an integer. We want this function to be callable from Python |
| 29 | as follows: |
| 30 | |
| 31 | \begin{verbatim} |
| 32 | >>> import spam |
| 33 | >>> status = spam.system("ls -l") |
| 34 | \end{verbatim} |
| 35 | |
| 36 | Begin by creating a file \file{spammodule.c}. (Historically, if a |
| 37 | module is called \samp{spam}, the C file containing its implementation |
| 38 | is called \file{spammodule.c}; if the module name is very long, like |
| 39 | \samp{spammify}, the module name can be just \file{spammify.c}.) |
| 40 | |
| 41 | The first line of our file can be: |
| 42 | |
| 43 | \begin{verbatim} |
| 44 | #include <Python.h> |
| 45 | \end{verbatim} |
| 46 | |
| 47 | which pulls in the Python API (you can add a comment describing the |
| 48 | purpose of the module and a copyright notice if you like). |
Fred Drake | 34c4320 | 2004-03-31 07:45:46 +0000 | [diff] [blame] | 49 | |
| 50 | \begin{notice}[warning] |
| 51 | Since Python may define some pre-processor definitions which affect |
| 52 | the standard headers on some systems, you \emph{must} include |
| 53 | \file{Python.h} before any standard headers are included. |
| 54 | \end{notice} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 55 | |
Fred Drake | 396ca57 | 2001-09-06 16:30:30 +0000 | [diff] [blame] | 56 | All user-visible symbols defined by \file{Python.h} have a prefix of |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 57 | \samp{Py} or \samp{PY}, except those defined in standard header files. |
| 58 | For convenience, and since they are used extensively by the Python |
| 59 | interpreter, \code{"Python.h"} includes a few standard header files: |
| 60 | \code{<stdio.h>}, \code{<string.h>}, \code{<errno.h>}, and |
| 61 | \code{<stdlib.h>}. If the latter header file does not exist on your |
| 62 | system, it declares the functions \cfunction{malloc()}, |
| 63 | \cfunction{free()} and \cfunction{realloc()} directly. |
| 64 | |
| 65 | The next thing we add to our module file is the C function that will |
| 66 | be called when the Python expression \samp{spam.system(\var{string})} |
| 67 | is evaluated (we'll see shortly how it ends up being called): |
| 68 | |
| 69 | \begin{verbatim} |
| 70 | static PyObject * |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 71 | spam_system(PyObject *self, PyObject *args) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 72 | { |
Brett Cannon | 289e4cb | 2004-06-29 03:48:23 +0000 | [diff] [blame] | 73 | const char *command; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 74 | int sts; |
| 75 | |
| 76 | if (!PyArg_ParseTuple(args, "s", &command)) |
| 77 | return NULL; |
| 78 | sts = system(command); |
| 79 | return Py_BuildValue("i", sts); |
| 80 | } |
| 81 | \end{verbatim} |
| 82 | |
| 83 | There is a straightforward translation from the argument list in |
| 84 | Python (for example, the single expression \code{"ls -l"}) to the |
| 85 | arguments passed to the C function. The C function always has two |
| 86 | arguments, conventionally named \var{self} and \var{args}. |
| 87 | |
| 88 | The \var{self} argument is only used when the C function implements a |
| 89 | built-in method, not a function. In the example, \var{self} will |
| 90 | always be a \NULL{} pointer, since we are defining a function, not a |
| 91 | method. (This is done so that the interpreter doesn't have to |
| 92 | understand two different types of C functions.) |
| 93 | |
| 94 | The \var{args} argument will be a pointer to a Python tuple object |
| 95 | containing the arguments. Each item of the tuple corresponds to an |
| 96 | argument in the call's argument list. The arguments are Python |
| 97 | objects --- in order to do anything with them in our C function we have |
| 98 | to convert them to C values. The function \cfunction{PyArg_ParseTuple()} |
| 99 | in the Python API checks the argument types and converts them to C |
| 100 | values. It uses a template string to determine the required types of |
| 101 | the arguments as well as the types of the C variables into which to |
| 102 | store the converted values. More about this later. |
| 103 | |
| 104 | \cfunction{PyArg_ParseTuple()} returns true (nonzero) if all arguments have |
| 105 | the right type and its components have been stored in the variables |
| 106 | whose addresses are passed. It returns false (zero) if an invalid |
| 107 | argument list was passed. In the latter case it also raises an |
| 108 | appropriate exception so the calling function can return |
| 109 | \NULL{} immediately (as we saw in the example). |
| 110 | |
| 111 | |
| 112 | \section{Intermezzo: Errors and Exceptions |
| 113 | \label{errors}} |
| 114 | |
| 115 | An important convention throughout the Python interpreter is the |
| 116 | following: when a function fails, it should set an exception condition |
| 117 | and return an error value (usually a \NULL{} pointer). Exceptions |
| 118 | are stored in a static global variable inside the interpreter; if this |
| 119 | variable is \NULL{} no exception has occurred. A second global |
| 120 | variable stores the ``associated value'' of the exception (the second |
| 121 | argument to \keyword{raise}). A third variable contains the stack |
| 122 | traceback in case the error originated in Python code. These three |
| 123 | variables are the C equivalents of the Python variables |
| 124 | \code{sys.exc_type}, \code{sys.exc_value} and \code{sys.exc_traceback} (see |
| 125 | the section on module \module{sys} in the |
| 126 | \citetitle[../lib/lib.html]{Python Library Reference}). It is |
| 127 | important to know about them to understand how errors are passed |
| 128 | around. |
| 129 | |
| 130 | The Python API defines a number of functions to set various types of |
| 131 | exceptions. |
| 132 | |
| 133 | The most common one is \cfunction{PyErr_SetString()}. Its arguments |
| 134 | are an exception object and a C string. The exception object is |
| 135 | usually a predefined object like \cdata{PyExc_ZeroDivisionError}. The |
| 136 | C string indicates the cause of the error and is converted to a |
| 137 | Python string object and stored as the ``associated value'' of the |
| 138 | exception. |
| 139 | |
| 140 | Another useful function is \cfunction{PyErr_SetFromErrno()}, which only |
| 141 | takes an exception argument and constructs the associated value by |
| 142 | inspection of the global variable \cdata{errno}. The most |
| 143 | general function is \cfunction{PyErr_SetObject()}, which takes two object |
| 144 | arguments, the exception and its associated value. You don't need to |
| 145 | \cfunction{Py_INCREF()} the objects passed to any of these functions. |
| 146 | |
| 147 | You can test non-destructively whether an exception has been set with |
| 148 | \cfunction{PyErr_Occurred()}. This returns the current exception object, |
| 149 | or \NULL{} if no exception has occurred. You normally don't need |
| 150 | to call \cfunction{PyErr_Occurred()} to see whether an error occurred in a |
| 151 | function call, since you should be able to tell from the return value. |
| 152 | |
| 153 | When a function \var{f} that calls another function \var{g} detects |
| 154 | that the latter fails, \var{f} should itself return an error value |
| 155 | (usually \NULL{} or \code{-1}). It should \emph{not} call one of the |
| 156 | \cfunction{PyErr_*()} functions --- one has already been called by \var{g}. |
| 157 | \var{f}'s caller is then supposed to also return an error indication |
| 158 | to \emph{its} caller, again \emph{without} calling \cfunction{PyErr_*()}, |
| 159 | and so on --- the most detailed cause of the error was already |
| 160 | reported by the function that first detected it. Once the error |
| 161 | reaches the Python interpreter's main loop, this aborts the currently |
| 162 | executing Python code and tries to find an exception handler specified |
| 163 | by the Python programmer. |
| 164 | |
| 165 | (There are situations where a module can actually give a more detailed |
| 166 | error message by calling another \cfunction{PyErr_*()} function, and in |
| 167 | such cases it is fine to do so. As a general rule, however, this is |
| 168 | not necessary, and can cause information about the cause of the error |
| 169 | to be lost: most operations can fail for a variety of reasons.) |
| 170 | |
| 171 | To ignore an exception set by a function call that failed, the exception |
| 172 | condition must be cleared explicitly by calling \cfunction{PyErr_Clear()}. |
| 173 | The only time C code should call \cfunction{PyErr_Clear()} is if it doesn't |
| 174 | want to pass the error on to the interpreter but wants to handle it |
| 175 | completely by itself (possibly by trying something else, or pretending |
| 176 | nothing went wrong). |
| 177 | |
| 178 | Every failing \cfunction{malloc()} call must be turned into an |
| 179 | exception --- the direct caller of \cfunction{malloc()} (or |
| 180 | \cfunction{realloc()}) must call \cfunction{PyErr_NoMemory()} and |
| 181 | return a failure indicator itself. All the object-creating functions |
| 182 | (for example, \cfunction{PyInt_FromLong()}) already do this, so this |
| 183 | note is only relevant to those who call \cfunction{malloc()} directly. |
| 184 | |
| 185 | Also note that, with the important exception of |
| 186 | \cfunction{PyArg_ParseTuple()} and friends, functions that return an |
| 187 | integer status usually return a positive value or zero for success and |
| 188 | \code{-1} for failure, like \UNIX{} system calls. |
| 189 | |
| 190 | Finally, be careful to clean up garbage (by making |
| 191 | \cfunction{Py_XDECREF()} or \cfunction{Py_DECREF()} calls for objects |
| 192 | you have already created) when you return an error indicator! |
| 193 | |
| 194 | The choice of which exception to raise is entirely yours. There are |
| 195 | predeclared C objects corresponding to all built-in Python exceptions, |
| 196 | such as \cdata{PyExc_ZeroDivisionError}, which you can use directly. |
| 197 | Of course, you should choose exceptions wisely --- don't use |
| 198 | \cdata{PyExc_TypeError} to mean that a file couldn't be opened (that |
| 199 | should probably be \cdata{PyExc_IOError}). If something's wrong with |
| 200 | the argument list, the \cfunction{PyArg_ParseTuple()} function usually |
| 201 | raises \cdata{PyExc_TypeError}. If you have an argument whose value |
| 202 | must be in a particular range or must satisfy other conditions, |
| 203 | \cdata{PyExc_ValueError} is appropriate. |
| 204 | |
| 205 | You can also define a new exception that is unique to your module. |
| 206 | For this, you usually declare a static object variable at the |
| 207 | beginning of your file: |
| 208 | |
| 209 | \begin{verbatim} |
| 210 | static PyObject *SpamError; |
| 211 | \end{verbatim} |
| 212 | |
| 213 | and initialize it in your module's initialization function |
| 214 | (\cfunction{initspam()}) with an exception object (leaving out |
| 215 | the error checking for now): |
| 216 | |
| 217 | \begin{verbatim} |
Mark Hammond | 8235ea1 | 2002-07-19 06:55:41 +0000 | [diff] [blame] | 218 | PyMODINIT_FUNC |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 219 | initspam(void) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 220 | { |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 221 | PyObject *m; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 222 | |
| 223 | m = Py_InitModule("spam", SpamMethods); |
Andrew M. Kuchling | 656aee7 | 2006-09-27 19:23:05 +0000 | [diff] [blame] | 224 | if (m == NULL) |
| 225 | return; |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 226 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 227 | SpamError = PyErr_NewException("spam.error", NULL, NULL); |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 228 | Py_INCREF(SpamError); |
| 229 | PyModule_AddObject(m, "error", SpamError); |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 230 | } |
| 231 | \end{verbatim} |
| 232 | |
| 233 | Note that the Python name for the exception object is |
| 234 | \exception{spam.error}. The \cfunction{PyErr_NewException()} function |
| 235 | may create a class with the base class being \exception{Exception} |
| 236 | (unless another class is passed in instead of \NULL), described in the |
| 237 | \citetitle[../lib/lib.html]{Python Library Reference} under ``Built-in |
| 238 | Exceptions.'' |
| 239 | |
| 240 | Note also that the \cdata{SpamError} variable retains a reference to |
| 241 | the newly created exception class; this is intentional! Since the |
| 242 | exception could be removed from the module by external code, an owned |
| 243 | reference to the class is needed to ensure that it will not be |
| 244 | discarded, causing \cdata{SpamError} to become a dangling pointer. |
| 245 | Should it become a dangling pointer, C code which raises the exception |
| 246 | could cause a core dump or other unintended side effects. |
| 247 | |
Brett Cannon | 555a964 | 2004-06-26 23:10:32 +0000 | [diff] [blame] | 248 | We discuss the use of PyMODINIT_FUNC as a function return type later in this |
| 249 | sample. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 250 | |
| 251 | \section{Back to the Example |
| 252 | \label{backToExample}} |
| 253 | |
| 254 | Going back to our example function, you should now be able to |
| 255 | understand this statement: |
| 256 | |
| 257 | \begin{verbatim} |
| 258 | if (!PyArg_ParseTuple(args, "s", &command)) |
| 259 | return NULL; |
| 260 | \end{verbatim} |
| 261 | |
| 262 | It returns \NULL{} (the error indicator for functions returning |
| 263 | object pointers) if an error is detected in the argument list, relying |
| 264 | on the exception set by \cfunction{PyArg_ParseTuple()}. Otherwise the |
| 265 | string value of the argument has been copied to the local variable |
| 266 | \cdata{command}. This is a pointer assignment and you are not supposed |
| 267 | to modify the string to which it points (so in Standard C, the variable |
| 268 | \cdata{command} should properly be declared as \samp{const char |
| 269 | *command}). |
| 270 | |
| 271 | The next statement is a call to the \UNIX{} function |
| 272 | \cfunction{system()}, passing it the string we just got from |
| 273 | \cfunction{PyArg_ParseTuple()}: |
| 274 | |
| 275 | \begin{verbatim} |
| 276 | sts = system(command); |
| 277 | \end{verbatim} |
| 278 | |
| 279 | Our \function{spam.system()} function must return the value of |
| 280 | \cdata{sts} as a Python object. This is done using the function |
| 281 | \cfunction{Py_BuildValue()}, which is something like the inverse of |
| 282 | \cfunction{PyArg_ParseTuple()}: it takes a format string and an |
| 283 | arbitrary number of C values, and returns a new Python object. |
| 284 | More info on \cfunction{Py_BuildValue()} is given later. |
| 285 | |
| 286 | \begin{verbatim} |
| 287 | return Py_BuildValue("i", sts); |
| 288 | \end{verbatim} |
| 289 | |
| 290 | In this case, it will return an integer object. (Yes, even integers |
| 291 | are objects on the heap in Python!) |
| 292 | |
| 293 | If you have a C function that returns no useful argument (a function |
| 294 | returning \ctype{void}), the corresponding Python function must return |
Brett Cannon | 634893d | 2004-06-27 04:28:00 +0000 | [diff] [blame] | 295 | \code{None}. You need this idiom to do so (which is implemented by the |
| 296 | \csimplemacro{Py_RETURN_NONE} macro): |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 297 | |
| 298 | \begin{verbatim} |
| 299 | Py_INCREF(Py_None); |
| 300 | return Py_None; |
| 301 | \end{verbatim} |
| 302 | |
| 303 | \cdata{Py_None} is the C name for the special Python object |
| 304 | \code{None}. It is a genuine Python object rather than a \NULL{} |
| 305 | pointer, which means ``error'' in most contexts, as we have seen. |
| 306 | |
| 307 | |
| 308 | \section{The Module's Method Table and Initialization Function |
| 309 | \label{methodTable}} |
| 310 | |
| 311 | I promised to show how \cfunction{spam_system()} is called from Python |
| 312 | programs. First, we need to list its name and address in a ``method |
| 313 | table'': |
| 314 | |
| 315 | \begin{verbatim} |
| 316 | static PyMethodDef SpamMethods[] = { |
| 317 | ... |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 318 | {"system", spam_system, METH_VARARGS, |
| 319 | "Execute a shell command."}, |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 320 | ... |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 321 | {NULL, NULL, 0, NULL} /* Sentinel */ |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 322 | }; |
| 323 | \end{verbatim} |
| 324 | |
| 325 | Note the third entry (\samp{METH_VARARGS}). This is a flag telling |
| 326 | the interpreter the calling convention to be used for the C |
| 327 | function. It should normally always be \samp{METH_VARARGS} or |
| 328 | \samp{METH_VARARGS | METH_KEYWORDS}; a value of \code{0} means that an |
| 329 | obsolete variant of \cfunction{PyArg_ParseTuple()} is used. |
| 330 | |
| 331 | When using only \samp{METH_VARARGS}, the function should expect |
| 332 | the Python-level parameters to be passed in as a tuple acceptable for |
| 333 | parsing via \cfunction{PyArg_ParseTuple()}; more information on this |
| 334 | function is provided below. |
| 335 | |
| 336 | The \constant{METH_KEYWORDS} bit may be set in the third field if |
| 337 | keyword arguments should be passed to the function. In this case, the |
| 338 | C function should accept a third \samp{PyObject *} parameter which |
| 339 | will be a dictionary of keywords. Use |
| 340 | \cfunction{PyArg_ParseTupleAndKeywords()} to parse the arguments to |
| 341 | such a function. |
| 342 | |
| 343 | The method table must be passed to the interpreter in the module's |
| 344 | initialization function. The initialization function must be named |
| 345 | \cfunction{init\var{name}()}, where \var{name} is the name of the |
| 346 | module, and should be the only non-\keyword{static} item defined in |
| 347 | the module file: |
| 348 | |
| 349 | \begin{verbatim} |
Mark Hammond | 8235ea1 | 2002-07-19 06:55:41 +0000 | [diff] [blame] | 350 | PyMODINIT_FUNC |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 351 | initspam(void) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 352 | { |
| 353 | (void) Py_InitModule("spam", SpamMethods); |
| 354 | } |
| 355 | \end{verbatim} |
| 356 | |
Mark Hammond | 8235ea1 | 2002-07-19 06:55:41 +0000 | [diff] [blame] | 357 | Note that PyMODINIT_FUNC declares the function as \code{void} return type, |
| 358 | declares any special linkage declarations required by the platform, and for |
Raymond Hettinger | f350160 | 2003-09-08 19:01:04 +0000 | [diff] [blame] | 359 | \Cpp{} declares the function as \code{extern "C"}. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 360 | |
| 361 | When the Python program imports module \module{spam} for the first |
| 362 | time, \cfunction{initspam()} is called. (See below for comments about |
| 363 | embedding Python.) It calls |
| 364 | \cfunction{Py_InitModule()}, which creates a ``module object'' (which |
| 365 | is inserted in the dictionary \code{sys.modules} under the key |
| 366 | \code{"spam"}), and inserts built-in function objects into the newly |
| 367 | created module based upon the table (an array of \ctype{PyMethodDef} |
| 368 | structures) that was passed as its second argument. |
| 369 | \cfunction{Py_InitModule()} returns a pointer to the module object |
Andrew M. Kuchling | 656aee7 | 2006-09-27 19:23:05 +0000 | [diff] [blame] | 370 | that it creates (which is unused here). It may abort with a fatal error |
| 371 | for certain errors, or return \NULL{} if the module could not be |
| 372 | initialized satisfactorily. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 373 | |
| 374 | When embedding Python, the \cfunction{initspam()} function is not |
| 375 | called automatically unless there's an entry in the |
| 376 | \cdata{_PyImport_Inittab} table. The easiest way to handle this is to |
| 377 | statically initialize your statically-linked modules by directly |
| 378 | calling \cfunction{initspam()} after the call to |
Brett Cannon | 7706c2d | 2005-02-13 22:50:04 +0000 | [diff] [blame] | 379 | \cfunction{Py_Initialize()}: |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 380 | |
| 381 | \begin{verbatim} |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 382 | int |
| 383 | main(int argc, char *argv[]) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 384 | { |
| 385 | /* Pass argv[0] to the Python interpreter */ |
| 386 | Py_SetProgramName(argv[0]); |
| 387 | |
| 388 | /* Initialize the Python interpreter. Required. */ |
| 389 | Py_Initialize(); |
| 390 | |
| 391 | /* Add a static module */ |
| 392 | initspam(); |
| 393 | \end{verbatim} |
| 394 | |
| 395 | An example may be found in the file \file{Demo/embed/demo.c} in the |
| 396 | Python source distribution. |
| 397 | |
Fred Drake | 0aa811c | 2001-10-20 04:24:09 +0000 | [diff] [blame] | 398 | \note{Removing entries from \code{sys.modules} or importing |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 399 | compiled modules into multiple interpreters within a process (or |
| 400 | following a \cfunction{fork()} without an intervening |
| 401 | \cfunction{exec()}) can create problems for some extension modules. |
| 402 | Extension module authors should exercise caution when initializing |
| 403 | internal data structures. |
| 404 | Note also that the \function{reload()} function can be used with |
| 405 | extension modules, and will call the module initialization function |
| 406 | (\cfunction{initspam()} in the example), but will not load the module |
| 407 | again if it was loaded from a dynamically loadable object file |
Fred Drake | 0aa811c | 2001-10-20 04:24:09 +0000 | [diff] [blame] | 408 | (\file{.so} on \UNIX, \file{.dll} on Windows).} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 409 | |
| 410 | A more substantial example module is included in the Python source |
| 411 | distribution as \file{Modules/xxmodule.c}. This file may be used as a |
| 412 | template or simply read as an example. The \program{modulator.py} |
| 413 | script included in the source distribution or Windows install provides |
| 414 | a simple graphical user interface for declaring the functions and |
| 415 | objects which a module should implement, and can generate a template |
| 416 | which can be filled in. The script lives in the |
| 417 | \file{Tools/modulator/} directory; see the \file{README} file there |
| 418 | for more information. |
| 419 | |
| 420 | |
| 421 | \section{Compilation and Linkage |
| 422 | \label{compilation}} |
| 423 | |
| 424 | There are two more things to do before you can use your new extension: |
| 425 | compiling and linking it with the Python system. If you use dynamic |
Fred Drake | 4e76555 | 2002-05-16 13:48:14 +0000 | [diff] [blame] | 426 | loading, the details may depend on the style of dynamic loading your |
| 427 | system uses; see the chapters about building extension modules |
| 428 | (chapter \ref{building}) and additional information that pertains only |
| 429 | to building on Windows (chapter \ref{building-on-windows}) for more |
| 430 | information about this. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 431 | |
| 432 | If you can't use dynamic loading, or if you want to make your module a |
| 433 | permanent part of the Python interpreter, you will have to change the |
| 434 | configuration setup and rebuild the interpreter. Luckily, this is |
Fred Drake | 4e76555 | 2002-05-16 13:48:14 +0000 | [diff] [blame] | 435 | very simple on \UNIX: just place your file (\file{spammodule.c} for |
| 436 | example) in the \file{Modules/} directory of an unpacked source |
| 437 | distribution, add a line to the file \file{Modules/Setup.local} |
| 438 | describing your file: |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 439 | |
| 440 | \begin{verbatim} |
| 441 | spam spammodule.o |
| 442 | \end{verbatim} |
| 443 | |
| 444 | and rebuild the interpreter by running \program{make} in the toplevel |
| 445 | directory. You can also run \program{make} in the \file{Modules/} |
| 446 | subdirectory, but then you must first rebuild \file{Makefile} |
| 447 | there by running `\program{make} Makefile'. (This is necessary each |
| 448 | time you change the \file{Setup} file.) |
| 449 | |
| 450 | If your module requires additional libraries to link with, these can |
| 451 | be listed on the line in the configuration file as well, for instance: |
| 452 | |
| 453 | \begin{verbatim} |
| 454 | spam spammodule.o -lX11 |
| 455 | \end{verbatim} |
| 456 | |
| 457 | \section{Calling Python Functions from C |
| 458 | \label{callingPython}} |
| 459 | |
| 460 | So far we have concentrated on making C functions callable from |
| 461 | Python. The reverse is also useful: calling Python functions from C. |
| 462 | This is especially the case for libraries that support so-called |
| 463 | ``callback'' functions. If a C interface makes use of callbacks, the |
| 464 | equivalent Python often needs to provide a callback mechanism to the |
| 465 | Python programmer; the implementation will require calling the Python |
| 466 | callback functions from a C callback. Other uses are also imaginable. |
| 467 | |
| 468 | Fortunately, the Python interpreter is easily called recursively, and |
| 469 | there is a standard interface to call a Python function. (I won't |
| 470 | dwell on how to call the Python parser with a particular string as |
| 471 | input --- if you're interested, have a look at the implementation of |
| 472 | the \programopt{-c} command line option in \file{Python/pythonmain.c} |
| 473 | from the Python source code.) |
| 474 | |
| 475 | Calling a Python function is easy. First, the Python program must |
| 476 | somehow pass you the Python function object. You should provide a |
| 477 | function (or some other interface) to do this. When this function is |
| 478 | called, save a pointer to the Python function object (be careful to |
| 479 | \cfunction{Py_INCREF()} it!) in a global variable --- or wherever you |
| 480 | see fit. For example, the following function might be part of a module |
| 481 | definition: |
| 482 | |
| 483 | \begin{verbatim} |
| 484 | static PyObject *my_callback = NULL; |
| 485 | |
| 486 | static PyObject * |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 487 | my_set_callback(PyObject *dummy, PyObject *args) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 488 | { |
| 489 | PyObject *result = NULL; |
| 490 | PyObject *temp; |
| 491 | |
| 492 | if (PyArg_ParseTuple(args, "O:set_callback", &temp)) { |
| 493 | if (!PyCallable_Check(temp)) { |
| 494 | PyErr_SetString(PyExc_TypeError, "parameter must be callable"); |
| 495 | return NULL; |
| 496 | } |
| 497 | Py_XINCREF(temp); /* Add a reference to new callback */ |
| 498 | Py_XDECREF(my_callback); /* Dispose of previous callback */ |
| 499 | my_callback = temp; /* Remember new callback */ |
| 500 | /* Boilerplate to return "None" */ |
| 501 | Py_INCREF(Py_None); |
| 502 | result = Py_None; |
| 503 | } |
| 504 | return result; |
| 505 | } |
| 506 | \end{verbatim} |
| 507 | |
| 508 | This function must be registered with the interpreter using the |
| 509 | \constant{METH_VARARGS} flag; this is described in section |
| 510 | \ref{methodTable}, ``The Module's Method Table and Initialization |
| 511 | Function.'' The \cfunction{PyArg_ParseTuple()} function and its |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 512 | arguments are documented in section~\ref{parseTuple}, ``Extracting |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 513 | Parameters in Extension Functions.'' |
| 514 | |
| 515 | The macros \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} |
| 516 | increment/decrement the reference count of an object and are safe in |
| 517 | the presence of \NULL{} pointers (but note that \var{temp} will not be |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 518 | \NULL{} in this context). More info on them in |
| 519 | section~\ref{refcounts}, ``Reference Counts.'' |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 520 | |
| 521 | Later, when it is time to call the function, you call the C function |
Fred Drake | 99181ac | 2001-11-29 05:02:34 +0000 | [diff] [blame] | 522 | \cfunction{PyEval_CallObject()}.\ttindex{PyEval_CallObject()} This |
| 523 | function has two arguments, both pointers to arbitrary Python objects: |
| 524 | the Python function, and the argument list. The argument list must |
| 525 | always be a tuple object, whose length is the number of arguments. To |
| 526 | call the Python function with no arguments, pass an empty tuple; to |
| 527 | call it with one argument, pass a singleton tuple. |
| 528 | \cfunction{Py_BuildValue()} returns a tuple when its format string |
| 529 | consists of zero or more format codes between parentheses. For |
| 530 | example: |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 531 | |
| 532 | \begin{verbatim} |
| 533 | int arg; |
| 534 | PyObject *arglist; |
| 535 | PyObject *result; |
| 536 | ... |
| 537 | arg = 123; |
| 538 | ... |
| 539 | /* Time to call the callback */ |
| 540 | arglist = Py_BuildValue("(i)", arg); |
| 541 | result = PyEval_CallObject(my_callback, arglist); |
| 542 | Py_DECREF(arglist); |
| 543 | \end{verbatim} |
| 544 | |
| 545 | \cfunction{PyEval_CallObject()} returns a Python object pointer: this is |
| 546 | the return value of the Python function. \cfunction{PyEval_CallObject()} is |
| 547 | ``reference-count-neutral'' with respect to its arguments. In the |
| 548 | example a new tuple was created to serve as the argument list, which |
| 549 | is \cfunction{Py_DECREF()}-ed immediately after the call. |
| 550 | |
| 551 | The return value of \cfunction{PyEval_CallObject()} is ``new'': either it |
| 552 | is a brand new object, or it is an existing object whose reference |
| 553 | count has been incremented. So, unless you want to save it in a |
| 554 | global variable, you should somehow \cfunction{Py_DECREF()} the result, |
| 555 | even (especially!) if you are not interested in its value. |
| 556 | |
| 557 | Before you do this, however, it is important to check that the return |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 558 | value isn't \NULL. If it is, the Python function terminated by |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 559 | raising an exception. If the C code that called |
| 560 | \cfunction{PyEval_CallObject()} is called from Python, it should now |
| 561 | return an error indication to its Python caller, so the interpreter |
| 562 | can print a stack trace, or the calling Python code can handle the |
| 563 | exception. If this is not possible or desirable, the exception should |
| 564 | be cleared by calling \cfunction{PyErr_Clear()}. For example: |
| 565 | |
| 566 | \begin{verbatim} |
| 567 | if (result == NULL) |
| 568 | return NULL; /* Pass error back */ |
| 569 | ...use result... |
| 570 | Py_DECREF(result); |
| 571 | \end{verbatim} |
| 572 | |
| 573 | Depending on the desired interface to the Python callback function, |
| 574 | you may also have to provide an argument list to |
| 575 | \cfunction{PyEval_CallObject()}. In some cases the argument list is |
| 576 | also provided by the Python program, through the same interface that |
| 577 | specified the callback function. It can then be saved and used in the |
| 578 | same manner as the function object. In other cases, you may have to |
| 579 | construct a new tuple to pass as the argument list. The simplest way |
| 580 | to do this is to call \cfunction{Py_BuildValue()}. For example, if |
| 581 | you want to pass an integral event code, you might use the following |
| 582 | code: |
| 583 | |
| 584 | \begin{verbatim} |
| 585 | PyObject *arglist; |
| 586 | ... |
| 587 | arglist = Py_BuildValue("(l)", eventcode); |
| 588 | result = PyEval_CallObject(my_callback, arglist); |
| 589 | Py_DECREF(arglist); |
| 590 | if (result == NULL) |
| 591 | return NULL; /* Pass error back */ |
| 592 | /* Here maybe use the result */ |
| 593 | Py_DECREF(result); |
| 594 | \end{verbatim} |
| 595 | |
| 596 | Note the placement of \samp{Py_DECREF(arglist)} immediately after the |
| 597 | call, before the error check! Also note that strictly spoken this |
| 598 | code is not complete: \cfunction{Py_BuildValue()} may run out of |
| 599 | memory, and this should be checked. |
| 600 | |
| 601 | |
| 602 | \section{Extracting Parameters in Extension Functions |
| 603 | \label{parseTuple}} |
| 604 | |
Fred Drake | e9fba91 | 2002-03-28 22:36:56 +0000 | [diff] [blame] | 605 | \ttindex{PyArg_ParseTuple()} |
| 606 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 607 | The \cfunction{PyArg_ParseTuple()} function is declared as follows: |
| 608 | |
| 609 | \begin{verbatim} |
| 610 | int PyArg_ParseTuple(PyObject *arg, char *format, ...); |
| 611 | \end{verbatim} |
| 612 | |
| 613 | The \var{arg} argument must be a tuple object containing an argument |
| 614 | list passed from Python to a C function. The \var{format} argument |
Fred Drake | 68304cc | 2002-04-05 23:01:14 +0000 | [diff] [blame] | 615 | must be a format string, whose syntax is explained in |
| 616 | ``\ulink{Parsing arguments and building |
| 617 | values}{../api/arg-parsing.html}'' in the |
| 618 | \citetitle[../api/api.html]{Python/C API Reference Manual}. The |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 619 | remaining arguments must be addresses of variables whose type is |
Fred Drake | 68304cc | 2002-04-05 23:01:14 +0000 | [diff] [blame] | 620 | determined by the format string. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 621 | |
| 622 | Note that while \cfunction{PyArg_ParseTuple()} checks that the Python |
| 623 | arguments have the required types, it cannot check the validity of the |
| 624 | addresses of C variables passed to the call: if you make mistakes |
| 625 | there, your code will probably crash or at least overwrite random bits |
| 626 | in memory. So be careful! |
| 627 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 628 | Note that any Python object references which are provided to the |
| 629 | caller are \emph{borrowed} references; do not decrement their |
| 630 | reference count! |
| 631 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 632 | Some example calls: |
| 633 | |
| 634 | \begin{verbatim} |
| 635 | int ok; |
| 636 | int i, j; |
| 637 | long k, l; |
Brett Cannon | 289e4cb | 2004-06-29 03:48:23 +0000 | [diff] [blame] | 638 | const char *s; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 639 | int size; |
| 640 | |
| 641 | ok = PyArg_ParseTuple(args, ""); /* No arguments */ |
| 642 | /* Python call: f() */ |
| 643 | \end{verbatim} |
| 644 | |
| 645 | \begin{verbatim} |
| 646 | ok = PyArg_ParseTuple(args, "s", &s); /* A string */ |
| 647 | /* Possible Python call: f('whoops!') */ |
| 648 | \end{verbatim} |
| 649 | |
| 650 | \begin{verbatim} |
| 651 | ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */ |
| 652 | /* Possible Python call: f(1, 2, 'three') */ |
| 653 | \end{verbatim} |
| 654 | |
| 655 | \begin{verbatim} |
| 656 | ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size); |
| 657 | /* A pair of ints and a string, whose size is also returned */ |
| 658 | /* Possible Python call: f((1, 2), 'three') */ |
| 659 | \end{verbatim} |
| 660 | |
| 661 | \begin{verbatim} |
| 662 | { |
Brett Cannon | 289e4cb | 2004-06-29 03:48:23 +0000 | [diff] [blame] | 663 | const char *file; |
| 664 | const char *mode = "r"; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 665 | int bufsize = 0; |
| 666 | ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize); |
| 667 | /* A string, and optionally another string and an integer */ |
| 668 | /* Possible Python calls: |
| 669 | f('spam') |
| 670 | f('spam', 'w') |
| 671 | f('spam', 'wb', 100000) */ |
| 672 | } |
| 673 | \end{verbatim} |
| 674 | |
| 675 | \begin{verbatim} |
| 676 | { |
| 677 | int left, top, right, bottom, h, v; |
| 678 | ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)", |
| 679 | &left, &top, &right, &bottom, &h, &v); |
| 680 | /* A rectangle and a point */ |
| 681 | /* Possible Python call: |
| 682 | f(((0, 0), (400, 300)), (10, 10)) */ |
| 683 | } |
| 684 | \end{verbatim} |
| 685 | |
| 686 | \begin{verbatim} |
| 687 | { |
| 688 | Py_complex c; |
| 689 | ok = PyArg_ParseTuple(args, "D:myfunction", &c); |
| 690 | /* a complex, also providing a function name for errors */ |
| 691 | /* Possible Python call: myfunction(1+2j) */ |
| 692 | } |
| 693 | \end{verbatim} |
| 694 | |
| 695 | |
| 696 | \section{Keyword Parameters for Extension Functions |
| 697 | \label{parseTupleAndKeywords}} |
| 698 | |
Fred Drake | e9fba91 | 2002-03-28 22:36:56 +0000 | [diff] [blame] | 699 | \ttindex{PyArg_ParseTupleAndKeywords()} |
| 700 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 701 | The \cfunction{PyArg_ParseTupleAndKeywords()} function is declared as |
| 702 | follows: |
| 703 | |
| 704 | \begin{verbatim} |
| 705 | int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 706 | char *format, char *kwlist[], ...); |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 707 | \end{verbatim} |
| 708 | |
| 709 | The \var{arg} and \var{format} parameters are identical to those of the |
| 710 | \cfunction{PyArg_ParseTuple()} function. The \var{kwdict} parameter |
| 711 | is the dictionary of keywords received as the third parameter from the |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 712 | Python runtime. The \var{kwlist} parameter is a \NULL-terminated |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 713 | list of strings which identify the parameters; the names are matched |
| 714 | with the type information from \var{format} from left to right. On |
| 715 | success, \cfunction{PyArg_ParseTupleAndKeywords()} returns true, |
| 716 | otherwise it returns false and raises an appropriate exception. |
| 717 | |
Fred Drake | 0aa811c | 2001-10-20 04:24:09 +0000 | [diff] [blame] | 718 | \note{Nested tuples cannot be parsed when using keyword |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 719 | arguments! Keyword parameters passed in which are not present in the |
Fred Drake | 0aa811c | 2001-10-20 04:24:09 +0000 | [diff] [blame] | 720 | \var{kwlist} will cause \exception{TypeError} to be raised.} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 721 | |
| 722 | Here is an example module which uses keywords, based on an example by |
| 723 | Geoff Philbrick (\email{philbrick@hks.com}):% |
| 724 | \index{Philbrick, Geoff} |
| 725 | |
| 726 | \begin{verbatim} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 727 | #include "Python.h" |
| 728 | |
| 729 | static PyObject * |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 730 | keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 731 | { |
| 732 | int voltage; |
| 733 | char *state = "a stiff"; |
| 734 | char *action = "voom"; |
| 735 | char *type = "Norwegian Blue"; |
| 736 | |
| 737 | static char *kwlist[] = {"voltage", "state", "action", "type", NULL}; |
| 738 | |
| 739 | if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, |
| 740 | &voltage, &state, &action, &type)) |
| 741 | return NULL; |
| 742 | |
| 743 | printf("-- This parrot wouldn't %s if you put %i Volts through it.\n", |
| 744 | action, voltage); |
| 745 | printf("-- Lovely plumage, the %s -- It's %s!\n", type, state); |
| 746 | |
| 747 | Py_INCREF(Py_None); |
| 748 | |
| 749 | return Py_None; |
| 750 | } |
| 751 | |
| 752 | static PyMethodDef keywdarg_methods[] = { |
| 753 | /* The cast of the function is necessary since PyCFunction values |
| 754 | * only take two PyObject* parameters, and keywdarg_parrot() takes |
| 755 | * three. |
| 756 | */ |
Fred Drake | 31f8483 | 2002-03-28 20:19:23 +0000 | [diff] [blame] | 757 | {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS, |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 758 | "Print a lovely skit to standard output."}, |
| 759 | {NULL, NULL, 0, NULL} /* sentinel */ |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 760 | }; |
Fred Drake | 31f8483 | 2002-03-28 20:19:23 +0000 | [diff] [blame] | 761 | \end{verbatim} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 762 | |
Fred Drake | 31f8483 | 2002-03-28 20:19:23 +0000 | [diff] [blame] | 763 | \begin{verbatim} |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 764 | void |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 765 | initkeywdarg(void) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 766 | { |
| 767 | /* Create the module and add the functions */ |
| 768 | Py_InitModule("keywdarg", keywdarg_methods); |
| 769 | } |
| 770 | \end{verbatim} |
| 771 | |
| 772 | |
| 773 | \section{Building Arbitrary Values |
| 774 | \label{buildValue}} |
| 775 | |
| 776 | This function is the counterpart to \cfunction{PyArg_ParseTuple()}. It is |
| 777 | declared as follows: |
| 778 | |
| 779 | \begin{verbatim} |
| 780 | PyObject *Py_BuildValue(char *format, ...); |
| 781 | \end{verbatim} |
| 782 | |
| 783 | It recognizes a set of format units similar to the ones recognized by |
| 784 | \cfunction{PyArg_ParseTuple()}, but the arguments (which are input to the |
| 785 | function, not output) must not be pointers, just values. It returns a |
| 786 | new Python object, suitable for returning from a C function called |
| 787 | from Python. |
| 788 | |
| 789 | One difference with \cfunction{PyArg_ParseTuple()}: while the latter |
| 790 | requires its first argument to be a tuple (since Python argument lists |
| 791 | are always represented as tuples internally), |
| 792 | \cfunction{Py_BuildValue()} does not always build a tuple. It builds |
| 793 | a tuple only if its format string contains two or more format units. |
| 794 | If the format string is empty, it returns \code{None}; if it contains |
| 795 | exactly one format unit, it returns whatever object is described by |
| 796 | that format unit. To force it to return a tuple of size 0 or one, |
| 797 | parenthesize the format string. |
| 798 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 799 | Examples (to the left the call, to the right the resulting Python value): |
| 800 | |
| 801 | \begin{verbatim} |
| 802 | Py_BuildValue("") None |
| 803 | Py_BuildValue("i", 123) 123 |
| 804 | Py_BuildValue("iii", 123, 456, 789) (123, 456, 789) |
| 805 | Py_BuildValue("s", "hello") 'hello' |
| 806 | Py_BuildValue("ss", "hello", "world") ('hello', 'world') |
| 807 | Py_BuildValue("s#", "hello", 4) 'hell' |
| 808 | Py_BuildValue("()") () |
| 809 | Py_BuildValue("(i)", 123) (123,) |
| 810 | Py_BuildValue("(ii)", 123, 456) (123, 456) |
| 811 | Py_BuildValue("(i,i)", 123, 456) (123, 456) |
| 812 | Py_BuildValue("[i,i]", 123, 456) [123, 456] |
| 813 | Py_BuildValue("{s:i,s:i}", |
| 814 | "abc", 123, "def", 456) {'abc': 123, 'def': 456} |
| 815 | Py_BuildValue("((ii)(ii)) (ii)", |
| 816 | 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6)) |
| 817 | \end{verbatim} |
| 818 | |
| 819 | |
| 820 | \section{Reference Counts |
| 821 | \label{refcounts}} |
| 822 | |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 823 | In languages like C or \Cpp, the programmer is responsible for |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 824 | dynamic allocation and deallocation of memory on the heap. In C, |
| 825 | this is done using the functions \cfunction{malloc()} and |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 826 | \cfunction{free()}. In \Cpp, the operators \keyword{new} and |
Michael W. Hudson | 241c2e9 | 2003-02-06 18:38:11 +0000 | [diff] [blame] | 827 | \keyword{delete} are used with essentially the same meaning and |
Michael W. Hudson | ff1f194 | 2003-11-07 11:45:34 +0000 | [diff] [blame] | 828 | we'll restrict the following discussion to the C case. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 829 | |
| 830 | Every block of memory allocated with \cfunction{malloc()} should |
| 831 | eventually be returned to the pool of available memory by exactly one |
| 832 | call to \cfunction{free()}. It is important to call |
| 833 | \cfunction{free()} at the right time. If a block's address is |
| 834 | forgotten but \cfunction{free()} is not called for it, the memory it |
| 835 | occupies cannot be reused until the program terminates. This is |
| 836 | called a \dfn{memory leak}. On the other hand, if a program calls |
| 837 | \cfunction{free()} for a block and then continues to use the block, it |
| 838 | creates a conflict with re-use of the block through another |
| 839 | \cfunction{malloc()} call. This is called \dfn{using freed memory}. |
| 840 | It has the same bad consequences as referencing uninitialized data --- |
| 841 | core dumps, wrong results, mysterious crashes. |
| 842 | |
| 843 | Common causes of memory leaks are unusual paths through the code. For |
| 844 | instance, a function may allocate a block of memory, do some |
| 845 | calculation, and then free the block again. Now a change in the |
| 846 | requirements for the function may add a test to the calculation that |
| 847 | detects an error condition and can return prematurely from the |
| 848 | function. It's easy to forget to free the allocated memory block when |
| 849 | taking this premature exit, especially when it is added later to the |
| 850 | code. Such leaks, once introduced, often go undetected for a long |
| 851 | time: the error exit is taken only in a small fraction of all calls, |
| 852 | and most modern machines have plenty of virtual memory, so the leak |
| 853 | only becomes apparent in a long-running process that uses the leaking |
| 854 | function frequently. Therefore, it's important to prevent leaks from |
| 855 | happening by having a coding convention or strategy that minimizes |
| 856 | this kind of errors. |
| 857 | |
| 858 | Since Python makes heavy use of \cfunction{malloc()} and |
| 859 | \cfunction{free()}, it needs a strategy to avoid memory leaks as well |
| 860 | as the use of freed memory. The chosen method is called |
| 861 | \dfn{reference counting}. The principle is simple: every object |
| 862 | contains a counter, which is incremented when a reference to the |
| 863 | object is stored somewhere, and which is decremented when a reference |
| 864 | to it is deleted. When the counter reaches zero, the last reference |
| 865 | to the object has been deleted and the object is freed. |
| 866 | |
| 867 | An alternative strategy is called \dfn{automatic garbage collection}. |
| 868 | (Sometimes, reference counting is also referred to as a garbage |
| 869 | collection strategy, hence my use of ``automatic'' to distinguish the |
| 870 | two.) The big advantage of automatic garbage collection is that the |
| 871 | user doesn't need to call \cfunction{free()} explicitly. (Another claimed |
| 872 | advantage is an improvement in speed or memory usage --- this is no |
| 873 | hard fact however.) The disadvantage is that for C, there is no |
| 874 | truly portable automatic garbage collector, while reference counting |
| 875 | can be implemented portably (as long as the functions \cfunction{malloc()} |
| 876 | and \cfunction{free()} are available --- which the C Standard guarantees). |
| 877 | Maybe some day a sufficiently portable automatic garbage collector |
| 878 | will be available for C. Until then, we'll have to live with |
| 879 | reference counts. |
| 880 | |
Fred Drake | 024e647 | 2001-12-07 17:30:40 +0000 | [diff] [blame] | 881 | While Python uses the traditional reference counting implementation, |
| 882 | it also offers a cycle detector that works to detect reference |
| 883 | cycles. This allows applications to not worry about creating direct |
| 884 | or indirect circular references; these are the weakness of garbage |
| 885 | collection implemented using only reference counting. Reference |
| 886 | cycles consist of objects which contain (possibly indirect) references |
Tim Peters | 874c4f0 | 2001-12-07 17:51:41 +0000 | [diff] [blame] | 887 | to themselves, so that each object in the cycle has a reference count |
Fred Drake | 024e647 | 2001-12-07 17:30:40 +0000 | [diff] [blame] | 888 | which is non-zero. Typical reference counting implementations are not |
Tim Peters | 874c4f0 | 2001-12-07 17:51:41 +0000 | [diff] [blame] | 889 | able to reclaim the memory belonging to any objects in a reference |
Fred Drake | 024e647 | 2001-12-07 17:30:40 +0000 | [diff] [blame] | 890 | cycle, or referenced from the objects in the cycle, even though there |
| 891 | are no further references to the cycle itself. |
| 892 | |
| 893 | The cycle detector is able to detect garbage cycles and can reclaim |
| 894 | them so long as there are no finalizers implemented in Python |
| 895 | (\method{__del__()} methods). When there are such finalizers, the |
| 896 | detector exposes the cycles through the \ulink{\module{gc} |
Guido van Rossum | 44b3f76 | 2001-12-07 17:57:56 +0000 | [diff] [blame] | 897 | module}{../lib/module-gc.html} (specifically, the \code{garbage} |
| 898 | variable in that module). The \module{gc} module also exposes a way |
| 899 | to run the detector (the \function{collect()} function), as well as |
Fred Drake | 024e647 | 2001-12-07 17:30:40 +0000 | [diff] [blame] | 900 | configuration interfaces and the ability to disable the detector at |
| 901 | runtime. The cycle detector is considered an optional component; |
Guido van Rossum | 44b3f76 | 2001-12-07 17:57:56 +0000 | [diff] [blame] | 902 | though it is included by default, it can be disabled at build time |
Fred Drake | 024e647 | 2001-12-07 17:30:40 +0000 | [diff] [blame] | 903 | using the \longprogramopt{without-cycle-gc} option to the |
| 904 | \program{configure} script on \UNIX{} platforms (including Mac OS X) |
| 905 | or by removing the definition of \code{WITH_CYCLE_GC} in the |
| 906 | \file{pyconfig.h} header on other platforms. If the cycle detector is |
| 907 | disabled in this way, the \module{gc} module will not be available. |
| 908 | |
| 909 | |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 910 | \subsection{Reference Counting in Python |
| 911 | \label{refcountsInPython}} |
| 912 | |
| 913 | There are two macros, \code{Py_INCREF(x)} and \code{Py_DECREF(x)}, |
| 914 | which handle the incrementing and decrementing of the reference count. |
| 915 | \cfunction{Py_DECREF()} also frees the object when the count reaches zero. |
| 916 | For flexibility, it doesn't call \cfunction{free()} directly --- rather, it |
| 917 | makes a call through a function pointer in the object's \dfn{type |
| 918 | object}. For this purpose (and others), every object also contains a |
| 919 | pointer to its type object. |
| 920 | |
| 921 | The big question now remains: when to use \code{Py_INCREF(x)} and |
| 922 | \code{Py_DECREF(x)}? Let's first introduce some terms. Nobody |
| 923 | ``owns'' an object; however, you can \dfn{own a reference} to an |
| 924 | object. An object's reference count is now defined as the number of |
| 925 | owned references to it. The owner of a reference is responsible for |
| 926 | calling \cfunction{Py_DECREF()} when the reference is no longer |
| 927 | needed. Ownership of a reference can be transferred. There are three |
| 928 | ways to dispose of an owned reference: pass it on, store it, or call |
| 929 | \cfunction{Py_DECREF()}. Forgetting to dispose of an owned reference |
| 930 | creates a memory leak. |
| 931 | |
| 932 | It is also possible to \dfn{borrow}\footnote{The metaphor of |
| 933 | ``borrowing'' a reference is not completely correct: the owner still |
| 934 | has a copy of the reference.} a reference to an object. The borrower |
| 935 | of a reference should not call \cfunction{Py_DECREF()}. The borrower must |
| 936 | not hold on to the object longer than the owner from which it was |
| 937 | borrowed. Using a borrowed reference after the owner has disposed of |
| 938 | it risks using freed memory and should be avoided |
| 939 | completely.\footnote{Checking that the reference count is at least 1 |
| 940 | \strong{does not work} --- the reference count itself could be in |
| 941 | freed memory and may thus be reused for another object!} |
| 942 | |
| 943 | The advantage of borrowing over owning a reference is that you don't |
| 944 | need to take care of disposing of the reference on all possible paths |
| 945 | through the code --- in other words, with a borrowed reference you |
| 946 | don't run the risk of leaking when a premature exit is taken. The |
| 947 | disadvantage of borrowing over leaking is that there are some subtle |
| 948 | situations where in seemingly correct code a borrowed reference can be |
| 949 | used after the owner from which it was borrowed has in fact disposed |
| 950 | of it. |
| 951 | |
| 952 | A borrowed reference can be changed into an owned reference by calling |
| 953 | \cfunction{Py_INCREF()}. This does not affect the status of the owner from |
| 954 | which the reference was borrowed --- it creates a new owned reference, |
| 955 | and gives full owner responsibilities (the new owner must |
| 956 | dispose of the reference properly, as well as the previous owner). |
| 957 | |
| 958 | |
| 959 | \subsection{Ownership Rules |
| 960 | \label{ownershipRules}} |
| 961 | |
| 962 | Whenever an object reference is passed into or out of a function, it |
| 963 | is part of the function's interface specification whether ownership is |
| 964 | transferred with the reference or not. |
| 965 | |
| 966 | Most functions that return a reference to an object pass on ownership |
| 967 | with the reference. In particular, all functions whose function it is |
| 968 | to create a new object, such as \cfunction{PyInt_FromLong()} and |
Fred Drake | 92024d1 | 2001-11-29 07:16:19 +0000 | [diff] [blame] | 969 | \cfunction{Py_BuildValue()}, pass ownership to the receiver. Even if |
| 970 | the object is not actually new, you still receive ownership of a new |
| 971 | reference to that object. For instance, \cfunction{PyInt_FromLong()} |
| 972 | maintains a cache of popular values and can return a reference to a |
| 973 | cached item. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 974 | |
| 975 | Many functions that extract objects from other objects also transfer |
| 976 | ownership with the reference, for instance |
| 977 | \cfunction{PyObject_GetAttrString()}. The picture is less clear, here, |
| 978 | however, since a few common routines are exceptions: |
| 979 | \cfunction{PyTuple_GetItem()}, \cfunction{PyList_GetItem()}, |
| 980 | \cfunction{PyDict_GetItem()}, and \cfunction{PyDict_GetItemString()} |
| 981 | all return references that you borrow from the tuple, list or |
| 982 | dictionary. |
| 983 | |
| 984 | The function \cfunction{PyImport_AddModule()} also returns a borrowed |
| 985 | reference, even though it may actually create the object it returns: |
| 986 | this is possible because an owned reference to the object is stored in |
| 987 | \code{sys.modules}. |
| 988 | |
| 989 | When you pass an object reference into another function, in general, |
| 990 | the function borrows the reference from you --- if it needs to store |
| 991 | it, it will use \cfunction{Py_INCREF()} to become an independent |
| 992 | owner. There are exactly two important exceptions to this rule: |
| 993 | \cfunction{PyTuple_SetItem()} and \cfunction{PyList_SetItem()}. These |
| 994 | functions take over ownership of the item passed to them --- even if |
| 995 | they fail! (Note that \cfunction{PyDict_SetItem()} and friends don't |
| 996 | take over ownership --- they are ``normal.'') |
| 997 | |
| 998 | When a C function is called from Python, it borrows references to its |
| 999 | arguments from the caller. The caller owns a reference to the object, |
| 1000 | so the borrowed reference's lifetime is guaranteed until the function |
| 1001 | returns. Only when such a borrowed reference must be stored or passed |
| 1002 | on, it must be turned into an owned reference by calling |
| 1003 | \cfunction{Py_INCREF()}. |
| 1004 | |
| 1005 | The object reference returned from a C function that is called from |
Raymond Hettinger | 6880431 | 2005-01-01 00:28:46 +0000 | [diff] [blame] | 1006 | Python must be an owned reference --- ownership is transferred from |
| 1007 | the function to its caller. |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1008 | |
| 1009 | |
| 1010 | \subsection{Thin Ice |
| 1011 | \label{thinIce}} |
| 1012 | |
| 1013 | There are a few situations where seemingly harmless use of a borrowed |
| 1014 | reference can lead to problems. These all have to do with implicit |
| 1015 | invocations of the interpreter, which can cause the owner of a |
| 1016 | reference to dispose of it. |
| 1017 | |
| 1018 | The first and most important case to know about is using |
| 1019 | \cfunction{Py_DECREF()} on an unrelated object while borrowing a |
| 1020 | reference to a list item. For instance: |
| 1021 | |
| 1022 | \begin{verbatim} |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 1023 | void |
| 1024 | bug(PyObject *list) |
| 1025 | { |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1026 | PyObject *item = PyList_GetItem(list, 0); |
| 1027 | |
| 1028 | PyList_SetItem(list, 1, PyInt_FromLong(0L)); |
| 1029 | PyObject_Print(item, stdout, 0); /* BUG! */ |
| 1030 | } |
| 1031 | \end{verbatim} |
| 1032 | |
| 1033 | This function first borrows a reference to \code{list[0]}, then |
| 1034 | replaces \code{list[1]} with the value \code{0}, and finally prints |
| 1035 | the borrowed reference. Looks harmless, right? But it's not! |
| 1036 | |
| 1037 | Let's follow the control flow into \cfunction{PyList_SetItem()}. The list |
| 1038 | owns references to all its items, so when item 1 is replaced, it has |
| 1039 | to dispose of the original item 1. Now let's suppose the original |
| 1040 | item 1 was an instance of a user-defined class, and let's further |
| 1041 | suppose that the class defined a \method{__del__()} method. If this |
| 1042 | class instance has a reference count of 1, disposing of it will call |
| 1043 | its \method{__del__()} method. |
| 1044 | |
| 1045 | Since it is written in Python, the \method{__del__()} method can execute |
| 1046 | arbitrary Python code. Could it perhaps do something to invalidate |
| 1047 | the reference to \code{item} in \cfunction{bug()}? You bet! Assuming |
| 1048 | that the list passed into \cfunction{bug()} is accessible to the |
| 1049 | \method{__del__()} method, it could execute a statement to the effect of |
| 1050 | \samp{del list[0]}, and assuming this was the last reference to that |
| 1051 | object, it would free the memory associated with it, thereby |
| 1052 | invalidating \code{item}. |
| 1053 | |
| 1054 | The solution, once you know the source of the problem, is easy: |
| 1055 | temporarily increment the reference count. The correct version of the |
| 1056 | function reads: |
| 1057 | |
| 1058 | \begin{verbatim} |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 1059 | void |
| 1060 | no_bug(PyObject *list) |
| 1061 | { |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1062 | PyObject *item = PyList_GetItem(list, 0); |
| 1063 | |
| 1064 | Py_INCREF(item); |
| 1065 | PyList_SetItem(list, 1, PyInt_FromLong(0L)); |
| 1066 | PyObject_Print(item, stdout, 0); |
| 1067 | Py_DECREF(item); |
| 1068 | } |
| 1069 | \end{verbatim} |
| 1070 | |
| 1071 | This is a true story. An older version of Python contained variants |
| 1072 | of this bug and someone spent a considerable amount of time in a C |
| 1073 | debugger to figure out why his \method{__del__()} methods would fail... |
| 1074 | |
| 1075 | The second case of problems with a borrowed reference is a variant |
| 1076 | involving threads. Normally, multiple threads in the Python |
| 1077 | interpreter can't get in each other's way, because there is a global |
| 1078 | lock protecting Python's entire object space. However, it is possible |
| 1079 | to temporarily release this lock using the macro |
Fred Drake | 375e302 | 2002-04-09 21:09:42 +0000 | [diff] [blame] | 1080 | \csimplemacro{Py_BEGIN_ALLOW_THREADS}, and to re-acquire it using |
| 1081 | \csimplemacro{Py_END_ALLOW_THREADS}. This is common around blocking |
| 1082 | I/O calls, to let other threads use the processor while waiting for |
| 1083 | the I/O to complete. Obviously, the following function has the same |
| 1084 | problem as the previous one: |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1085 | |
| 1086 | \begin{verbatim} |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 1087 | void |
| 1088 | bug(PyObject *list) |
| 1089 | { |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1090 | PyObject *item = PyList_GetItem(list, 0); |
| 1091 | Py_BEGIN_ALLOW_THREADS |
| 1092 | ...some blocking I/O call... |
| 1093 | Py_END_ALLOW_THREADS |
| 1094 | PyObject_Print(item, stdout, 0); /* BUG! */ |
| 1095 | } |
| 1096 | \end{verbatim} |
| 1097 | |
| 1098 | |
| 1099 | \subsection{NULL Pointers |
| 1100 | \label{nullPointers}} |
| 1101 | |
| 1102 | In general, functions that take object references as arguments do not |
| 1103 | expect you to pass them \NULL{} pointers, and will dump core (or |
| 1104 | cause later core dumps) if you do so. Functions that return object |
| 1105 | references generally return \NULL{} only to indicate that an |
| 1106 | exception occurred. The reason for not testing for \NULL{} |
| 1107 | arguments is that functions often pass the objects they receive on to |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 1108 | other function --- if each function were to test for \NULL, |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1109 | there would be a lot of redundant tests and the code would run more |
| 1110 | slowly. |
| 1111 | |
| 1112 | It is better to test for \NULL{} only at the ``source:'' when a |
| 1113 | pointer that may be \NULL{} is received, for example, from |
| 1114 | \cfunction{malloc()} or from a function that may raise an exception. |
| 1115 | |
| 1116 | The macros \cfunction{Py_INCREF()} and \cfunction{Py_DECREF()} |
| 1117 | do not check for \NULL{} pointers --- however, their variants |
| 1118 | \cfunction{Py_XINCREF()} and \cfunction{Py_XDECREF()} do. |
| 1119 | |
| 1120 | The macros for checking for a particular object type |
| 1121 | (\code{Py\var{type}_Check()}) don't check for \NULL{} pointers --- |
| 1122 | again, there is much code that calls several of these in a row to test |
| 1123 | an object against various different expected types, and this would |
| 1124 | generate redundant tests. There are no variants with \NULL{} |
| 1125 | checking. |
| 1126 | |
| 1127 | The C function calling mechanism guarantees that the argument list |
| 1128 | passed to C functions (\code{args} in the examples) is never |
| 1129 | \NULL{} --- in fact it guarantees that it is always a tuple.\footnote{ |
| 1130 | These guarantees don't hold when you use the ``old'' style |
| 1131 | calling convention --- this is still found in much existing code.} |
| 1132 | |
| 1133 | It is a severe error to ever let a \NULL{} pointer ``escape'' to |
| 1134 | the Python user. |
| 1135 | |
| 1136 | % Frank Stajano: |
| 1137 | % A pedagogically buggy example, along the lines of the previous listing, |
| 1138 | % would be helpful here -- showing in more concrete terms what sort of |
| 1139 | % actions could cause the problem. I can't very well imagine it from the |
| 1140 | % description. |
| 1141 | |
| 1142 | |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 1143 | \section{Writing Extensions in \Cpp |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1144 | \label{cplusplus}} |
| 1145 | |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 1146 | It is possible to write extension modules in \Cpp. Some restrictions |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1147 | apply. If the main program (the Python interpreter) is compiled and |
| 1148 | linked by the C compiler, global or static objects with constructors |
| 1149 | cannot be used. This is not a problem if the main program is linked |
| 1150 | by the \Cpp{} compiler. Functions that will be called by the |
Raymond Hettinger | 6880431 | 2005-01-01 00:28:46 +0000 | [diff] [blame] | 1151 | Python interpreter (in particular, module initialization functions) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1152 | have to be declared using \code{extern "C"}. |
| 1153 | It is unnecessary to enclose the Python header files in |
| 1154 | \code{extern "C" \{...\}} --- they use this form already if the symbol |
| 1155 | \samp{__cplusplus} is defined (all recent \Cpp{} compilers define this |
| 1156 | symbol). |
| 1157 | |
| 1158 | |
| 1159 | \section{Providing a C API for an Extension Module |
| 1160 | \label{using-cobjects}} |
| 1161 | \sectionauthor{Konrad Hinsen}{hinsen@cnrs-orleans.fr} |
| 1162 | |
| 1163 | Many extension modules just provide new functions and types to be |
| 1164 | used from Python, but sometimes the code in an extension module can |
| 1165 | be useful for other extension modules. For example, an extension |
| 1166 | module could implement a type ``collection'' which works like lists |
| 1167 | without order. Just like the standard Python list type has a C API |
| 1168 | which permits extension modules to create and manipulate lists, this |
| 1169 | new collection type should have a set of C functions for direct |
| 1170 | manipulation from other extension modules. |
| 1171 | |
| 1172 | At first sight this seems easy: just write the functions (without |
| 1173 | declaring them \keyword{static}, of course), provide an appropriate |
| 1174 | header file, and document the C API. And in fact this would work if |
| 1175 | all extension modules were always linked statically with the Python |
| 1176 | interpreter. When modules are used as shared libraries, however, the |
| 1177 | symbols defined in one module may not be visible to another module. |
| 1178 | The details of visibility depend on the operating system; some systems |
| 1179 | use one global namespace for the Python interpreter and all extension |
| 1180 | modules (Windows, for example), whereas others require an explicit |
| 1181 | list of imported symbols at module link time (AIX is one example), or |
| 1182 | offer a choice of different strategies (most Unices). And even if |
| 1183 | symbols are globally visible, the module whose functions one wishes to |
| 1184 | call might not have been loaded yet! |
| 1185 | |
| 1186 | Portability therefore requires not to make any assumptions about |
| 1187 | symbol visibility. This means that all symbols in extension modules |
| 1188 | should be declared \keyword{static}, except for the module's |
| 1189 | initialization function, in order to avoid name clashes with other |
| 1190 | extension modules (as discussed in section~\ref{methodTable}). And it |
| 1191 | means that symbols that \emph{should} be accessible from other |
| 1192 | extension modules must be exported in a different way. |
| 1193 | |
| 1194 | Python provides a special mechanism to pass C-level information |
| 1195 | (pointers) from one extension module to another one: CObjects. |
| 1196 | A CObject is a Python data type which stores a pointer (\ctype{void |
| 1197 | *}). CObjects can only be created and accessed via their C API, but |
| 1198 | they can be passed around like any other Python object. In particular, |
| 1199 | they can be assigned to a name in an extension module's namespace. |
| 1200 | Other extension modules can then import this module, retrieve the |
| 1201 | value of this name, and then retrieve the pointer from the CObject. |
| 1202 | |
| 1203 | There are many ways in which CObjects can be used to export the C API |
| 1204 | of an extension module. Each name could get its own CObject, or all C |
| 1205 | API pointers could be stored in an array whose address is published in |
| 1206 | a CObject. And the various tasks of storing and retrieving the pointers |
| 1207 | can be distributed in different ways between the module providing the |
| 1208 | code and the client modules. |
| 1209 | |
| 1210 | The following example demonstrates an approach that puts most of the |
| 1211 | burden on the writer of the exporting module, which is appropriate |
| 1212 | for commonly used library modules. It stores all C API pointers |
| 1213 | (just one in the example!) in an array of \ctype{void} pointers which |
| 1214 | becomes the value of a CObject. The header file corresponding to |
| 1215 | the module provides a macro that takes care of importing the module |
| 1216 | and retrieving its C API pointers; client modules only have to call |
| 1217 | this macro before accessing the C API. |
| 1218 | |
| 1219 | The exporting module is a modification of the \module{spam} module from |
| 1220 | section~\ref{simpleExample}. The function \function{spam.system()} |
| 1221 | does not call the C library function \cfunction{system()} directly, |
| 1222 | but a function \cfunction{PySpam_System()}, which would of course do |
| 1223 | something more complicated in reality (such as adding ``spam'' to |
| 1224 | every command). This function \cfunction{PySpam_System()} is also |
| 1225 | exported to other extension modules. |
| 1226 | |
| 1227 | The function \cfunction{PySpam_System()} is a plain C function, |
| 1228 | declared \keyword{static} like everything else: |
| 1229 | |
| 1230 | \begin{verbatim} |
| 1231 | static int |
Brett Cannon | 289e4cb | 2004-06-29 03:48:23 +0000 | [diff] [blame] | 1232 | PySpam_System(const char *command) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1233 | { |
| 1234 | return system(command); |
| 1235 | } |
| 1236 | \end{verbatim} |
| 1237 | |
| 1238 | The function \cfunction{spam_system()} is modified in a trivial way: |
| 1239 | |
| 1240 | \begin{verbatim} |
| 1241 | static PyObject * |
Fred Drake | 723f94b | 2002-06-22 01:42:00 +0000 | [diff] [blame] | 1242 | spam_system(PyObject *self, PyObject *args) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1243 | { |
Brett Cannon | 289e4cb | 2004-06-29 03:48:23 +0000 | [diff] [blame] | 1244 | const char *command; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1245 | int sts; |
| 1246 | |
| 1247 | if (!PyArg_ParseTuple(args, "s", &command)) |
| 1248 | return NULL; |
| 1249 | sts = PySpam_System(command); |
| 1250 | return Py_BuildValue("i", sts); |
| 1251 | } |
| 1252 | \end{verbatim} |
| 1253 | |
| 1254 | In the beginning of the module, right after the line |
| 1255 | |
| 1256 | \begin{verbatim} |
| 1257 | #include "Python.h" |
| 1258 | \end{verbatim} |
| 1259 | |
| 1260 | two more lines must be added: |
| 1261 | |
| 1262 | \begin{verbatim} |
| 1263 | #define SPAM_MODULE |
| 1264 | #include "spammodule.h" |
| 1265 | \end{verbatim} |
| 1266 | |
| 1267 | The \code{\#define} is used to tell the header file that it is being |
| 1268 | included in the exporting module, not a client module. Finally, |
| 1269 | the module's initialization function must take care of initializing |
| 1270 | the C API pointer array: |
| 1271 | |
| 1272 | \begin{verbatim} |
Mark Hammond | 8235ea1 | 2002-07-19 06:55:41 +0000 | [diff] [blame] | 1273 | PyMODINIT_FUNC |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 1274 | initspam(void) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1275 | { |
| 1276 | PyObject *m; |
| 1277 | static void *PySpam_API[PySpam_API_pointers]; |
| 1278 | PyObject *c_api_object; |
| 1279 | |
| 1280 | m = Py_InitModule("spam", SpamMethods); |
Andrew M. Kuchling | 656aee7 | 2006-09-27 19:23:05 +0000 | [diff] [blame] | 1281 | if (m == NULL) |
| 1282 | return; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1283 | |
| 1284 | /* Initialize the C API pointer array */ |
| 1285 | PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; |
| 1286 | |
| 1287 | /* Create a CObject containing the API pointer array's address */ |
| 1288 | c_api_object = PyCObject_FromVoidPtr((void *)PySpam_API, NULL); |
| 1289 | |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 1290 | if (c_api_object != NULL) |
| 1291 | PyModule_AddObject(m, "_C_API", c_api_object); |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1292 | } |
| 1293 | \end{verbatim} |
| 1294 | |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 1295 | Note that \code{PySpam_API} is declared \keyword{static}; otherwise |
| 1296 | the pointer array would disappear when \function{initspam()} terminates! |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1297 | |
| 1298 | The bulk of the work is in the header file \file{spammodule.h}, |
| 1299 | which looks like this: |
| 1300 | |
| 1301 | \begin{verbatim} |
| 1302 | #ifndef Py_SPAMMODULE_H |
| 1303 | #define Py_SPAMMODULE_H |
| 1304 | #ifdef __cplusplus |
| 1305 | extern "C" { |
| 1306 | #endif |
| 1307 | |
| 1308 | /* Header file for spammodule */ |
| 1309 | |
| 1310 | /* C API functions */ |
| 1311 | #define PySpam_System_NUM 0 |
| 1312 | #define PySpam_System_RETURN int |
Georg Brandl | b6c1bb8 | 2005-06-05 10:56:59 +0000 | [diff] [blame] | 1313 | #define PySpam_System_PROTO (const char *command) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1314 | |
| 1315 | /* Total number of C API pointers */ |
| 1316 | #define PySpam_API_pointers 1 |
| 1317 | |
| 1318 | |
| 1319 | #ifdef SPAM_MODULE |
| 1320 | /* This section is used when compiling spammodule.c */ |
| 1321 | |
| 1322 | static PySpam_System_RETURN PySpam_System PySpam_System_PROTO; |
| 1323 | |
| 1324 | #else |
| 1325 | /* This section is used in modules that use spammodule's API */ |
| 1326 | |
| 1327 | static void **PySpam_API; |
| 1328 | |
| 1329 | #define PySpam_System \ |
| 1330 | (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM]) |
| 1331 | |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 1332 | /* Return -1 and set exception on error, 0 on success. */ |
| 1333 | static int |
| 1334 | import_spam(void) |
| 1335 | { |
| 1336 | PyObject *module = PyImport_ImportModule("spam"); |
| 1337 | |
| 1338 | if (module != NULL) { |
| 1339 | PyObject *c_api_object = PyObject_GetAttrString(module, "_C_API"); |
| 1340 | if (c_api_object == NULL) |
| 1341 | return -1; |
| 1342 | if (PyCObject_Check(c_api_object)) |
| 1343 | PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); |
| 1344 | Py_DECREF(c_api_object); |
| 1345 | } |
| 1346 | return 0; |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1347 | } |
| 1348 | |
| 1349 | #endif |
| 1350 | |
| 1351 | #ifdef __cplusplus |
| 1352 | } |
| 1353 | #endif |
| 1354 | |
Raymond Hettinger | f9c2eda | 2003-05-20 05:31:16 +0000 | [diff] [blame] | 1355 | #endif /* !defined(Py_SPAMMODULE_H) */ |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1356 | \end{verbatim} |
| 1357 | |
| 1358 | All that a client module must do in order to have access to the |
| 1359 | function \cfunction{PySpam_System()} is to call the function (or |
| 1360 | rather macro) \cfunction{import_spam()} in its initialization |
| 1361 | function: |
| 1362 | |
| 1363 | \begin{verbatim} |
Mark Hammond | 8235ea1 | 2002-07-19 06:55:41 +0000 | [diff] [blame] | 1364 | PyMODINIT_FUNC |
Fred Drake | ef6373a | 2001-11-17 06:50:42 +0000 | [diff] [blame] | 1365 | initclient(void) |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1366 | { |
| 1367 | PyObject *m; |
| 1368 | |
Andrew M. Kuchling | 656aee7 | 2006-09-27 19:23:05 +0000 | [diff] [blame] | 1369 | m = Py_InitModule("client", ClientMethods); |
| 1370 | if (m == NULL) |
| 1371 | return; |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 1372 | if (import_spam() < 0) |
| 1373 | return; |
| 1374 | /* additional initialization can happen here */ |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1375 | } |
| 1376 | \end{verbatim} |
| 1377 | |
| 1378 | The main disadvantage of this approach is that the file |
| 1379 | \file{spammodule.h} is rather complicated. However, the |
| 1380 | basic structure is the same for each function that is |
| 1381 | exported, so it has to be learned only once. |
| 1382 | |
| 1383 | Finally it should be mentioned that CObjects offer additional |
| 1384 | functionality, which is especially useful for memory allocation and |
| 1385 | deallocation of the pointer stored in a CObject. The details |
| 1386 | are described in the \citetitle[../api/api.html]{Python/C API |
Fred Drake | 63e40a5 | 2002-04-12 19:08:31 +0000 | [diff] [blame] | 1387 | Reference Manual} in the section |
| 1388 | ``\ulink{CObjects}{../api/cObjects.html}'' and in the implementation |
| 1389 | of CObjects (files \file{Include/cobject.h} and |
Fred Drake | cc8f44b | 2001-08-20 19:30:29 +0000 | [diff] [blame] | 1390 | \file{Objects/cobject.c} in the Python source code distribution). |