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