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