Changeset 391 for python/trunk/Doc/extending/extending.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/extending/extending.rst
r2 r391 36 36 Let's create an extension module called ``spam`` (the favorite food of Monty 37 37 Python fans...) and let's say we want to create a Python interface to the C 38 library function :c func:`system`. [#]_ This function takes a null-terminated38 library function :c:func:`system`. [#]_ This function takes a null-terminated 39 39 character string as argument and returns an integer. We want this function to 40 40 be callable from Python as follows:: … … 66 66 includes a few standard header files: ``<stdio.h>``, ``<string.h>``, 67 67 ``<errno.h>``, and ``<stdlib.h>``. If the latter header file does not exist on 68 your system, it declares the functions :c func:`malloc`, :cfunc:`free` and69 :c func:`realloc` directly.68 your system, it declares the functions :c:func:`malloc`, :c:func:`free` and 69 :c:func:`realloc` directly. 70 70 71 71 The next thing we add to our module file is the C function that will be called … … 90 90 and *args*. 91 91 92 The *self* argument is only used when the C function implements a built-in 93 method, not a function. In the example, *self* will always be a *NULL* pointer, 94 since we are defining a function, not a method. (This is done so that the 95 interpreter doesn't have to understand two different types of C functions.) 92 The *self* argument points to the module object for module-level functions; 93 for a method it would point to the object instance. 96 94 97 95 The *args* argument will be a pointer to a Python tuple object containing the … … 99 97 argument list. The arguments are Python objects --- in order to do anything 100 98 with them in our C function we have to convert them to C values. The function 101 :c func:`PyArg_ParseTuple` in the Python API checks the argument types and99 :c:func:`PyArg_ParseTuple` in the Python API checks the argument types and 102 100 converts them to C values. It uses a template string to determine the required 103 101 types of the arguments as well as the types of the C variables into which to 104 102 store the converted values. More about this later. 105 103 106 :c func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right104 :c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right 107 105 type and its components have been stored in the variables whose addresses are 108 106 passed. It returns false (zero) if an invalid argument list was passed. In the … … 130 128 The Python API defines a number of functions to set various types of exceptions. 131 129 132 The most common one is :c func:`PyErr_SetString`. Its arguments are an exception130 The most common one is :c:func:`PyErr_SetString`. Its arguments are an exception 133 131 object and a C string. The exception object is usually a predefined object like 134 :c data:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error132 :c:data:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error 135 133 and is converted to a Python string object and stored as the "associated value" 136 134 of the exception. 137 135 138 Another useful function is :c func:`PyErr_SetFromErrno`, which only takes an136 Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an 139 137 exception argument and constructs the associated value by inspection of the 140 global variable :c data:`errno`. The most general function is141 :c func:`PyErr_SetObject`, which takes two object arguments, the exception and142 its associated value. You don't need to :c func:`Py_INCREF` the objects passed138 global variable :c:data:`errno`. The most general function is 139 :c:func:`PyErr_SetObject`, which takes two object arguments, the exception and 140 its associated value. You don't need to :c:func:`Py_INCREF` the objects passed 143 141 to any of these functions. 144 142 145 143 You can test non-destructively whether an exception has been set with 146 :c func:`PyErr_Occurred`. This returns the current exception object, or *NULL*144 :c:func:`PyErr_Occurred`. This returns the current exception object, or *NULL* 147 145 if no exception has occurred. You normally don't need to call 148 :c func:`PyErr_Occurred` to see whether an error occurred in a function call,146 :c:func:`PyErr_Occurred` to see whether an error occurred in a function call, 149 147 since you should be able to tell from the return value. 150 148 151 149 When a function *f* that calls another function *g* detects that the latter 152 150 fails, *f* should itself return an error value (usually *NULL* or ``-1``). It 153 should *not* call one of the :c func:`PyErr_\*` functions --- one has already151 should *not* call one of the :c:func:`PyErr_\*` functions --- one has already 154 152 been called by *g*. *f*'s caller is then supposed to also return an error 155 indication to *its* caller, again *without* calling :c func:`PyErr_\*`, and so on153 indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on 156 154 --- the most detailed cause of the error was already reported by the function 157 155 that first detected it. Once the error reaches the Python interpreter's main … … 160 158 161 159 (There are situations where a module can actually give a more detailed error 162 message by calling another :c func:`PyErr_\*` function, and in such cases it is160 message by calling another :c:func:`PyErr_\*` function, and in such cases it is 163 161 fine to do so. As a general rule, however, this is not necessary, and can cause 164 162 information about the cause of the error to be lost: most operations can fail … … 166 164 167 165 To ignore an exception set by a function call that failed, the exception 168 condition must be cleared explicitly by calling :c func:`PyErr_Clear`. The only169 time C code should call :c func:`PyErr_Clear` is if it doesn't want to pass the166 condition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The only 167 time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the 170 168 error on to the interpreter but wants to handle it completely by itself 171 169 (possibly by trying something else, or pretending nothing went wrong). 172 170 173 Every failing :c func:`malloc` call must be turned into an exception --- the174 direct caller of :c func:`malloc` (or :cfunc:`realloc`) must call175 :c func:`PyErr_NoMemory` and return a failure indicator itself. All the176 object-creating functions (for example, :c func:`PyInt_FromLong`) already do177 this, so this note is only relevant to those who call :c func:`malloc` directly.178 179 Also note that, with the important exception of :c func:`PyArg_ParseTuple` and171 Every failing :c:func:`malloc` call must be turned into an exception --- the 172 direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call 173 :c:func:`PyErr_NoMemory` and return a failure indicator itself. All the 174 object-creating functions (for example, :c:func:`PyInt_FromLong`) already do 175 this, so this note is only relevant to those who call :c:func:`malloc` directly. 176 177 Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and 180 178 friends, functions that return an integer status usually return a positive value 181 179 or zero for success and ``-1`` for failure, like Unix system calls. 182 180 183 Finally, be careful to clean up garbage (by making :c func:`Py_XDECREF` or184 :c func:`Py_DECREF` calls for objects you have already created) when you return181 Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or 182 :c:func:`Py_DECREF` calls for objects you have already created) when you return 185 183 an error indicator! 186 184 187 185 The choice of which exception to raise is entirely yours. There are predeclared 188 186 C objects corresponding to all built-in Python exceptions, such as 189 :c data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you190 should choose exceptions wisely --- don't use :c data:`PyExc_TypeError` to mean191 that a file couldn't be opened (that should probably be :c data:`PyExc_IOError`).192 If something's wrong with the argument list, the :c func:`PyArg_ParseTuple`193 function usually raises :c data:`PyExc_TypeError`. If you have an argument whose187 :c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you 188 should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean 189 that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`). 190 If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple` 191 function usually raises :c:data:`PyExc_TypeError`. If you have an argument whose 194 192 value must be in a particular range or must satisfy other conditions, 195 :c data:`PyExc_ValueError` is appropriate.193 :c:data:`PyExc_ValueError` is appropriate. 196 194 197 195 You can also define a new exception that is unique to your module. For this, you … … 200 198 static PyObject *SpamError; 201 199 202 and initialize it in your module's initialization function (:c func:`initspam`)200 and initialize it in your module's initialization function (:c:func:`initspam`) 203 201 with an exception object (leaving out the error checking for now):: 204 202 … … 218 216 219 217 Note that the Python name for the exception object is :exc:`spam.error`. The 220 :c func:`PyErr_NewException` function may create a class with the base class218 :c:func:`PyErr_NewException` function may create a class with the base class 221 219 being :exc:`Exception` (unless another class is passed in instead of *NULL*), 222 220 described in :ref:`bltin-exceptions`. 223 221 224 Note also that the :c data:`SpamError` variable retains a reference to the newly222 Note also that the :c:data:`SpamError` variable retains a reference to the newly 225 223 created exception class; this is intentional! Since the exception could be 226 224 removed from the module by external code, an owned reference to the class is 227 needed to ensure that it will not be discarded, causing :c data:`SpamError` to225 needed to ensure that it will not be discarded, causing :c:data:`SpamError` to 228 226 become a dangling pointer. Should it become a dangling pointer, C code which 229 227 raises the exception could cause a core dump or other unintended side effects. 230 228 231 We discuss the use of PyMODINIT_FUNCas a function return type later in this229 We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this 232 230 sample. 231 232 The :exc:`spam.error` exception can be raised in your extension module using a 233 call to :c:func:`PyErr_SetString` as shown below:: 234 235 static PyObject * 236 spam_system(PyObject *self, PyObject *args) 237 { 238 const char *command; 239 int sts; 240 241 if (!PyArg_ParseTuple(args, "s", &command)) 242 return NULL; 243 sts = system(command); 244 if (sts < 0) { 245 PyErr_SetString(SpamError, "System command failed"); 246 return NULL; 247 } 248 return PyLong_FromLong(sts); 249 } 233 250 234 251 … … 246 263 It returns *NULL* (the error indicator for functions returning object pointers) 247 264 if an error is detected in the argument list, relying on the exception set by 248 :c func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been249 copied to the local variable :c data:`command`. This is a pointer assignment and265 :c:func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been 266 copied to the local variable :c:data:`command`. This is a pointer assignment and 250 267 you are not supposed to modify the string to which it points (so in Standard C, 251 the variable :c data:`command` should properly be declared as ``const char268 the variable :c:data:`command` should properly be declared as ``const char 252 269 *command``). 253 270 254 The next statement is a call to the Unix function :c func:`system`, passing it255 the string we just got from :c func:`PyArg_ParseTuple`::271 The next statement is a call to the Unix function :c:func:`system`, passing it 272 the string we just got from :c:func:`PyArg_ParseTuple`:: 256 273 257 274 sts = system(command); 258 275 259 Our :func:`spam.system` function must return the value of :c data:`sts` as a260 Python object. This is done using the function :c func:`Py_BuildValue`, which is261 something like the inverse of :c func:`PyArg_ParseTuple`: it takes a format276 Our :func:`spam.system` function must return the value of :c:data:`sts` as a 277 Python object. This is done using the function :c:func:`Py_BuildValue`, which is 278 something like the inverse of :c:func:`PyArg_ParseTuple`: it takes a format 262 279 string and an arbitrary number of C values, and returns a new Python object. 263 More info on :c func:`Py_BuildValue` is given later. ::280 More info on :c:func:`Py_BuildValue` is given later. :: 264 281 265 282 return Py_BuildValue("i", sts); … … 269 286 270 287 If you have a C function that returns no useful argument (a function returning 271 :c type:`void`), the corresponding Python function must return ``None``. You272 need this idiom to do so (which is implemented by the :c macro:`Py_RETURN_NONE`288 :c:type:`void`), the corresponding Python function must return ``None``. You 289 need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE` 273 290 macro):: 274 291 … … 276 293 return Py_None; 277 294 278 :c data:`Py_None` is the C name for the special Python object ``None``. It is a295 :c:data:`Py_None` is the C name for the special Python object ``None``. It is a 279 296 genuine Python object rather than a *NULL* pointer, which means "error" in most 280 297 contexts, as we have seen. … … 286 303 ===================================================== 287 304 288 I promised to show how :c func:`spam_system` is called from Python programs.305 I promised to show how :c:func:`spam_system` is called from Python programs. 289 306 First, we need to list its name and address in a "method table":: 290 307 … … 300 317 the calling convention to be used for the C function. It should normally always 301 318 be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means 302 that an obsolete variant of :c func:`PyArg_ParseTuple` is used.319 that an obsolete variant of :c:func:`PyArg_ParseTuple` is used. 303 320 304 321 When using only ``METH_VARARGS``, the function should expect the Python-level 305 322 parameters to be passed in as a tuple acceptable for parsing via 306 :c func:`PyArg_ParseTuple`; more information on this function is provided below.323 :c:func:`PyArg_ParseTuple`; more information on this function is provided below. 307 324 308 325 The :const:`METH_KEYWORDS` bit may be set in the third field if keyword 309 326 arguments should be passed to the function. In this case, the C function should 310 327 accept a third ``PyObject *`` parameter which will be a dictionary of keywords. 311 Use :c func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a328 Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a 312 329 function. 313 330 314 331 The method table must be passed to the interpreter in the module's 315 332 initialization function. The initialization function must be named 316 :c func:`initname`, where *name* is the name of the module, and should be the333 :c:func:`initname`, where *name* is the name of the module, and should be the 317 334 only non-\ ``static`` item defined in the module file:: 318 335 … … 328 345 329 346 When the Python program imports module :mod:`spam` for the first time, 330 :c func:`initspam` is called. (See below for comments about embedding Python.)331 It calls :c func:`Py_InitModule`, which creates a "module object" (which is347 :c:func:`initspam` is called. (See below for comments about embedding Python.) 348 It calls :c:func:`Py_InitModule`, which creates a "module object" (which is 332 349 inserted in the dictionary ``sys.modules`` under the key ``"spam"``), and 333 350 inserts built-in function objects into the newly created module based upon the 334 table (an array of :c type:`PyMethodDef` structures) that was passed as its335 second argument. :c func:`Py_InitModule` returns a pointer to the module object351 table (an array of :c:type:`PyMethodDef` structures) that was passed as its 352 second argument. :c:func:`Py_InitModule` returns a pointer to the module object 336 353 that it creates (which is unused here). It may abort with a fatal error for 337 354 certain errors, or return *NULL* if the module could not be initialized 338 355 satisfactorily. 339 356 340 When embedding Python, the :c func:`initspam` function is not called341 automatically unless there's an entry in the :c data:`_PyImport_Inittab` table.357 When embedding Python, the :c:func:`initspam` function is not called 358 automatically unless there's an entry in the :c:data:`_PyImport_Inittab` table. 342 359 The easiest way to handle this is to statically initialize your 343 statically-linked modules by directly calling :c func:`initspam` after the call344 to :c func:`Py_Initialize`::360 statically-linked modules by directly calling :c:func:`initspam` after the call 361 to :c:func:`Py_Initialize`:: 345 362 346 363 int … … 356 373 initspam(); 357 374 375 ... 376 358 377 An example may be found in the file :file:`Demo/embed/demo.c` in the Python 359 378 source distribution. … … 362 381 363 382 Removing entries from ``sys.modules`` or importing compiled modules into 364 multiple interpreters within a process (or following a :c func:`fork` without an365 intervening :c func:`exec`) can create problems for some extension modules.383 multiple interpreters within a process (or following a :c:func:`fork` without an 384 intervening :c:func:`exec`) can create problems for some extension modules. 366 385 Extension module authors should exercise caution when initializing internal data 367 386 structures. Note also that the :func:`reload` function can be used with 368 387 extension modules, and will call the module initialization function 369 (:c func:`initspam` in the example), but will not load the module again if it was388 (:c:func:`initspam` in the example), but will not load the module again if it was 370 389 loaded from a dynamically loadable object file (:file:`.so` on Unix, 371 390 :file:`.dll` on Windows). … … 373 392 A more substantial example module is included in the Python source distribution 374 393 as :file:`Modules/xxmodule.c`. This file may be used as a template or simply 375 read as an example. The :program:`modulator.py` script included in the source 376 distribution or Windows install provides a simple graphical user interface for 377 declaring the functions and objects which a module should implement, and can 378 generate a template which can be filled in. The script lives in the 379 :file:`Tools/modulator/` directory; see the :file:`README` file there for more 380 information. 394 read as an example. 381 395 382 396 … … 436 450 you the Python function object. You should provide a function (or some other 437 451 interface) to do this. When this function is called, save a pointer to the 438 Python function object (be careful to :c func:`Py_INCREF` it!) in a global452 Python function object (be careful to :c:func:`Py_INCREF` it!) in a global 439 453 variable --- or wherever you see fit. For example, the following function might 440 454 be part of a module definition:: … … 465 479 This function must be registered with the interpreter using the 466 480 :const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The 467 :c func:`PyArg_ParseTuple` function and its arguments are documented in section481 :c:func:`PyArg_ParseTuple` function and its arguments are documented in section 468 482 :ref:`parsetuple`. 469 483 470 The macros :c func:`Py_XINCREF` and :cfunc:`Py_XDECREF` increment/decrement the484 The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the 471 485 reference count of an object and are safe in the presence of *NULL* pointers 472 486 (but note that *temp* will not be *NULL* in this context). More info on them … … 476 490 477 491 Later, when it is time to call the function, you call the C function 478 :c func:`PyObject_CallObject`. This function has two arguments, both pointers to492 :c:func:`PyObject_CallObject`. This function has two arguments, both pointers to 479 493 arbitrary Python objects: the Python function, and the argument list. The 480 494 argument list must always be a tuple object, whose length is the number of 481 495 arguments. To call the Python function with no arguments, pass in NULL, or 482 496 an empty tuple; to call it with one argument, pass a singleton tuple. 483 :c func:`Py_BuildValue` returns a tuple when its format string consists of zero497 :c:func:`Py_BuildValue` returns a tuple when its format string consists of zero 484 498 or more format codes between parentheses. For example:: 485 499 … … 495 509 Py_DECREF(arglist); 496 510 497 :c func:`PyObject_CallObject` returns a Python object pointer: this is the return498 value of the Python function. :c func:`PyObject_CallObject` is511 :c:func:`PyObject_CallObject` returns a Python object pointer: this is the return 512 value of the Python function. :c:func:`PyObject_CallObject` is 499 513 "reference-count-neutral" with respect to its arguments. In the example a new 500 tuple was created to serve as the argument list, which is :c func:`Py_DECREF`\501 -ed immediately after the call.502 503 The return value of :c func:`PyObject_CallObject` is "new": either it is a brand514 tuple was created to serve as the argument list, which is :c:func:`Py_DECREF`\ 515 -ed immediately after the :c:func:`PyObject_CallObject` call. 516 517 The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand 504 518 new object, or it is an existing object whose reference count has been 505 519 incremented. So, unless you want to save it in a global variable, you should 506 somehow :c func:`Py_DECREF` the result, even (especially!) if you are not520 somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not 507 521 interested in its value. 508 522 509 523 Before you do this, however, it is important to check that the return value 510 524 isn't *NULL*. If it is, the Python function terminated by raising an exception. 511 If the C code that called :c func:`PyObject_CallObject` is called from Python, it525 If the C code that called :c:func:`PyObject_CallObject` is called from Python, it 512 526 should now return an error indication to its Python caller, so the interpreter 513 527 can print a stack trace, or the calling Python code can handle the exception. 514 528 If this is not possible or desirable, the exception should be cleared by calling 515 :c func:`PyErr_Clear`. For example::529 :c:func:`PyErr_Clear`. For example:: 516 530 517 531 if (result == NULL) … … 521 535 522 536 Depending on the desired interface to the Python callback function, you may also 523 have to provide an argument list to :c func:`PyObject_CallObject`. In some cases537 have to provide an argument list to :c:func:`PyObject_CallObject`. In some cases 524 538 the argument list is also provided by the Python program, through the same 525 539 interface that specified the callback function. It can then be saved and used 526 540 in the same manner as the function object. In other cases, you may have to 527 541 construct a new tuple to pass as the argument list. The simplest way to do this 528 is to call :c func:`Py_BuildValue`. For example, if you want to pass an integral542 is to call :c:func:`Py_BuildValue`. For example, if you want to pass an integral 529 543 event code, you might use the following code:: 530 544 … … 541 555 Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before 542 556 the error check! Also note that strictly speaking this code is not complete: 543 :c func:`Py_BuildValue` may run out of memory, and this should be checked.557 :c:func:`Py_BuildValue` may run out of memory, and this should be checked. 544 558 545 559 You may also call a function with keyword arguments by using 546 :c func:`PyObject_Call`, which supports arguments and keyword arguments. As in547 the above example, we use :c func:`Py_BuildValue` to construct the dictionary. ::560 :c:func:`PyObject_Call`, which supports arguments and keyword arguments. As in 561 the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. :: 548 562 549 563 PyObject *dict; … … 565 579 .. index:: single: PyArg_ParseTuple() 566 580 567 The :c func:`PyArg_ParseTuple` function is declared as follows::581 The :c:func:`PyArg_ParseTuple` function is declared as follows:: 568 582 569 583 int PyArg_ParseTuple(PyObject *arg, char *format, ...); … … 575 589 determined by the format string. 576 590 577 Note that while :c func:`PyArg_ParseTuple` checks that the Python arguments have591 Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have 578 592 the required types, it cannot check the validity of the addresses of C variables 579 593 passed to the call: if you make mistakes there, your code will probably crash or … … 652 666 .. index:: single: PyArg_ParseTupleAndKeywords() 653 667 654 The :c func:`PyArg_ParseTupleAndKeywords` function is declared as follows::668 The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows:: 655 669 656 670 int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, … … 658 672 659 673 The *arg* and *format* parameters are identical to those of the 660 :c func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of674 :c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of 661 675 keywords received as the third parameter from the Python runtime. The *kwlist* 662 676 parameter is a *NULL*-terminated list of strings which identify the parameters; 663 677 the names are matched with the type information from *format* from left to 664 right. On success, :c func:`PyArg_ParseTupleAndKeywords` returns true, otherwise678 right. On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise 665 679 it returns false and raises an appropriate exception. 666 680 … … 726 740 ========================= 727 741 728 This function is the counterpart to :c func:`PyArg_ParseTuple`. It is declared742 This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is declared 729 743 as follows:: 730 744 … … 732 746 733 747 It recognizes a set of format units similar to the ones recognized by 734 :c func:`PyArg_ParseTuple`, but the arguments (which are input to the function,748 :c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function, 735 749 not output) must not be pointers, just values. It returns a new Python object, 736 750 suitable for returning from a C function called from Python. 737 751 738 One difference with :c func:`PyArg_ParseTuple`: while the latter requires its752 One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its 739 753 first argument to be a tuple (since Python argument lists are always represented 740 as tuples internally), :c func:`Py_BuildValue` does not always build a tuple. It754 as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple. It 741 755 builds a tuple only if its format string contains two or more format units. If 742 756 the format string is empty, it returns ``None``; if it contains exactly one … … 770 784 In languages like C or C++, the programmer is responsible for dynamic allocation 771 785 and deallocation of memory on the heap. In C, this is done using the functions 772 :c func:`malloc` and :cfunc:`free`. In C++, the operators ``new`` and786 :c:func:`malloc` and :c:func:`free`. In C++, the operators ``new`` and 773 787 ``delete`` are used with essentially the same meaning and we'll restrict 774 788 the following discussion to the C case. 775 789 776 Every block of memory allocated with :c func:`malloc` should eventually be777 returned to the pool of available memory by exactly one call to :c func:`free`.778 It is important to call :c func:`free` at the right time. If a block's address779 is forgotten but :c func:`free` is not called for it, the memory it occupies790 Every block of memory allocated with :c:func:`malloc` should eventually be 791 returned to the pool of available memory by exactly one call to :c:func:`free`. 792 It is important to call :c:func:`free` at the right time. If a block's address 793 is forgotten but :c:func:`free` is not called for it, the memory it occupies 780 794 cannot be reused until the program terminates. This is called a :dfn:`memory 781 leak`. On the other hand, if a program calls :c func:`free` for a block and then795 leak`. On the other hand, if a program calls :c:func:`free` for a block and then 782 796 continues to use the block, it creates a conflict with re-use of the block 783 through another :c func:`malloc` call. This is called :dfn:`using freed memory`.797 through another :c:func:`malloc` call. This is called :dfn:`using freed memory`. 784 798 It has the same bad consequences as referencing uninitialized data --- core 785 799 dumps, wrong results, mysterious crashes. … … 798 812 strategy that minimizes this kind of errors. 799 813 800 Since Python makes heavy use of :c func:`malloc` and :cfunc:`free`, it needs a814 Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a 801 815 strategy to avoid memory leaks as well as the use of freed memory. The chosen 802 816 method is called :dfn:`reference counting`. The principle is simple: every … … 810 824 strategy, hence my use of "automatic" to distinguish the two.) The big 811 825 advantage of automatic garbage collection is that the user doesn't need to call 812 :c func:`free` explicitly. (Another claimed advantage is an improvement in speed826 :c:func:`free` explicitly. (Another claimed advantage is an improvement in speed 813 827 or memory usage --- this is no hard fact however.) The disadvantage is that for 814 828 C, there is no truly portable automatic garbage collector, while reference 815 counting can be implemented portably (as long as the functions :c func:`malloc`816 and :c func:`free` are available --- which the C Standard guarantees). Maybe some829 counting can be implemented portably (as long as the functions :c:func:`malloc` 830 and :c:func:`free` are available --- which the C Standard guarantees). Maybe some 817 831 day a sufficiently portable automatic garbage collector will be available for C. 818 832 Until then, we'll have to live with reference counts. … … 832 846 as there are no finalizers implemented in Python (:meth:`__del__` methods). 833 847 When there are such finalizers, the detector exposes the cycles through the 834 :mod:`gc` module (specifically, the 835 ``garbage`` variable in that module). The :mod:`gc` module also exposes a way 836 to run the detector (the :func:`collect` function), as well as configuration848 :mod:`gc` module (specifically, the :attr:`~gc.garbage` variable in that module). 849 The :mod:`gc` module also exposes a way to run the detector (the 850 :func:`~gc.collect` function), as well as configuration 837 851 interfaces and the ability to disable the detector at runtime. The cycle 838 852 detector is considered an optional component; though it is included by default, … … 850 864 851 865 There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the 852 incrementing and decrementing of the reference count. :c func:`Py_DECREF` also866 incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also 853 867 frees the object when the count reaches zero. For flexibility, it doesn't call 854 :c func:`free` directly --- rather, it makes a call through a function pointer in868 :c:func:`free` directly --- rather, it makes a call through a function pointer in 855 869 the object's :dfn:`type object`. For this purpose (and others), every object 856 870 also contains a pointer to its type object. … … 860 874 :dfn:`own a reference` to an object. An object's reference count is now defined 861 875 as the number of owned references to it. The owner of a reference is 862 responsible for calling :c func:`Py_DECREF` when the reference is no longer876 responsible for calling :c:func:`Py_DECREF` when the reference is no longer 863 877 needed. Ownership of a reference can be transferred. There are three ways to 864 dispose of an owned reference: pass it on, store it, or call :c func:`Py_DECREF`.878 dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`. 865 879 Forgetting to dispose of an owned reference creates a memory leak. 866 880 867 881 It is also possible to :dfn:`borrow` [#]_ a reference to an object. The 868 borrower of a reference should not call :c func:`Py_DECREF`. The borrower must882 borrower of a reference should not call :c:func:`Py_DECREF`. The borrower must 869 883 not hold on to the object longer than the owner from which it was borrowed. 870 884 Using a borrowed reference after the owner has disposed of it risks using freed … … 880 894 881 895 A borrowed reference can be changed into an owned reference by calling 882 :c func:`Py_INCREF`. This does not affect the status of the owner from which the896 :c:func:`Py_INCREF`. This does not affect the status of the owner from which the 883 897 reference was borrowed --- it creates a new owned reference, and gives full 884 898 owner responsibilities (the new owner must dispose of the reference properly, as … … 897 911 Most functions that return a reference to an object pass on ownership with the 898 912 reference. In particular, all functions whose function it is to create a new 899 object, such as :c func:`PyInt_FromLong` and :cfunc:`Py_BuildValue`, pass913 object, such as :c:func:`PyInt_FromLong` and :c:func:`Py_BuildValue`, pass 900 914 ownership to the receiver. Even if the object is not actually new, you still 901 915 receive ownership of a new reference to that object. For instance, 902 :c func:`PyInt_FromLong` maintains a cache of popular values and can return a916 :c:func:`PyInt_FromLong` maintains a cache of popular values and can return a 903 917 reference to a cached item. 904 918 905 919 Many functions that extract objects from other objects also transfer ownership 906 with the reference, for instance :c func:`PyObject_GetAttrString`. The picture920 with the reference, for instance :c:func:`PyObject_GetAttrString`. The picture 907 921 is less clear, here, however, since a few common routines are exceptions: 908 :c func:`PyTuple_GetItem`, :cfunc:`PyList_GetItem`, :cfunc:`PyDict_GetItem`, and909 :c func:`PyDict_GetItemString` all return references that you borrow from the922 :c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and 923 :c:func:`PyDict_GetItemString` all return references that you borrow from the 910 924 tuple, list or dictionary. 911 925 912 The function :c func:`PyImport_AddModule` also returns a borrowed reference, even926 The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even 913 927 though it may actually create the object it returns: this is possible because an 914 928 owned reference to the object is stored in ``sys.modules``. … … 916 930 When you pass an object reference into another function, in general, the 917 931 function borrows the reference from you --- if it needs to store it, it will use 918 :c func:`Py_INCREF` to become an independent owner. There are exactly two919 important exceptions to this rule: :c func:`PyTuple_SetItem` and920 :c func:`PyList_SetItem`. These functions take over ownership of the item passed921 to them --- even if they fail! (Note that :c func:`PyDict_SetItem` and friends932 :c:func:`Py_INCREF` to become an independent owner. There are exactly two 933 important exceptions to this rule: :c:func:`PyTuple_SetItem` and 934 :c:func:`PyList_SetItem`. These functions take over ownership of the item passed 935 to them --- even if they fail! (Note that :c:func:`PyDict_SetItem` and friends 922 936 don't take over ownership --- they are "normal.") 923 937 … … 926 940 reference's lifetime is guaranteed until the function returns. Only when such a 927 941 borrowed reference must be stored or passed on, it must be turned into an owned 928 reference by calling :c func:`Py_INCREF`.942 reference by calling :c:func:`Py_INCREF`. 929 943 930 944 The object reference returned from a C function that is called from Python must … … 942 956 interpreter, which can cause the owner of a reference to dispose of it. 943 957 944 The first and most important case to know about is using :c func:`Py_DECREF` on958 The first and most important case to know about is using :c:func:`Py_DECREF` on 945 959 an unrelated object while borrowing a reference to a list item. For instance:: 946 960 … … 958 972 Looks harmless, right? But it's not! 959 973 960 Let's follow the control flow into :c func:`PyList_SetItem`. The list owns974 Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns 961 975 references to all its items, so when item 1 is replaced, it has to dispose of 962 976 the original item 1. Now let's suppose the original item 1 was an instance of a … … 967 981 Since it is written in Python, the :meth:`__del__` method can execute arbitrary 968 982 Python code. Could it perhaps do something to invalidate the reference to 969 ``item`` in :c func:`bug`? You bet! Assuming that the list passed into970 :c func:`bug` is accessible to the :meth:`__del__` method, it could execute a983 ``item`` in :c:func:`bug`? You bet! Assuming that the list passed into 984 :c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a 971 985 statement to the effect of ``del list[0]``, and assuming this was the last 972 986 reference to that object, it would free the memory associated with it, thereby … … 995 1009 other's way, because there is a global lock protecting Python's entire object 996 1010 space. However, it is possible to temporarily release this lock using the macro 997 :c macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using998 :c macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to1011 :c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using 1012 :c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to 999 1013 let other threads use the processor while waiting for the I/O to complete. 1000 1014 Obviously, the following function has the same problem as the previous one:: … … 1025 1039 1026 1040 It is better to test for *NULL* only at the "source:" when a pointer that may be 1027 *NULL* is received, for example, from :c func:`malloc` or from a function that1041 *NULL* is received, for example, from :c:func:`malloc` or from a function that 1028 1042 may raise an exception. 1029 1043 1030 The macros :c func:`Py_INCREF` and :cfunc:`Py_DECREF` do not check for *NULL*1031 pointers --- however, their variants :c func:`Py_XINCREF` and :cfunc:`Py_XDECREF`1044 The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for *NULL* 1045 pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` 1032 1046 do. 1033 1047 … … 1066 1080 1067 1081 1068 .. _using-c objects:1082 .. _using-capsules: 1069 1083 1070 1084 Providing a C API for an Extension Module … … 1102 1116 1103 1117 Python provides a special mechanism to pass C-level information (pointers) from 1104 one extension module to another one: C Objects. A CObjectis a Python data type1105 which stores a pointer (:c type:`void \*`). CObjects can only be created and1118 one extension module to another one: Capsules. A Capsule is a Python data type 1119 which stores a pointer (:c:type:`void \*`). Capsules can only be created and 1106 1120 accessed via their C API, but they can be passed around like any other Python 1107 1121 object. In particular, they can be assigned to a name in an extension module's 1108 1122 namespace. Other extension modules can then import this module, retrieve the 1109 value of this name, and then retrieve the pointer from the C Object.1110 1111 There are many ways in which C Objects can be used to export the C API of an1112 extension module. Each name could get its own CObject, or all C API pointers1113 could be stored in an array whose address is published in a C Object. And the1123 value of this name, and then retrieve the pointer from the Capsule. 1124 1125 There are many ways in which Capsules can be used to export the C API of an 1126 extension module. Each function could get its own Capsule, or all C API pointers 1127 could be stored in an array whose address is published in a Capsule. And the 1114 1128 various tasks of storing and retrieving the pointers can be distributed in 1115 1129 different ways between the module providing the code and the client modules. 1130 1131 Whichever method you choose, it's important to name your Capsules properly. 1132 The function :c:func:`PyCapsule_New` takes a name parameter 1133 (:c:type:`const char \*`); you're permitted to pass in a *NULL* name, but 1134 we strongly encourage you to specify a name. Properly named Capsules provide 1135 a degree of runtime type-safety; there is no feasible way to tell one unnamed 1136 Capsule from another. 1137 1138 In particular, Capsules used to expose C APIs should be given a name following 1139 this convention:: 1140 1141 modulename.attributename 1142 1143 The convenience function :c:func:`PyCapsule_Import` makes it easy to 1144 load a C API provided via a Capsule, but only if the Capsule's name 1145 matches this convention. This behavior gives C API users a high degree 1146 of certainty that the Capsule they load contains the correct C API. 1116 1147 1117 1148 The following example demonstrates an approach that puts most of the burden on 1118 1149 the writer of the exporting module, which is appropriate for commonly used 1119 1150 library modules. It stores all C API pointers (just one in the example!) in an 1120 array of :c type:`void` pointers which becomes the value of a CObject. The header1151 array of :c:type:`void` pointers which becomes the value of a Capsule. The header 1121 1152 file corresponding to the module provides a macro that takes care of importing 1122 1153 the module and retrieving its C API pointers; client modules only have to call … … 1125 1156 The exporting module is a modification of the :mod:`spam` module from section 1126 1157 :ref:`extending-simpleexample`. The function :func:`spam.system` does not call 1127 the C library function :c func:`system` directly, but a function1128 :c func:`PySpam_System`, which would of course do something more complicated in1158 the C library function :c:func:`system` directly, but a function 1159 :c:func:`PySpam_System`, which would of course do something more complicated in 1129 1160 reality (such as adding "spam" to every command). This function 1130 :c func:`PySpam_System` is also exported to other extension modules.1131 1132 The function :c func:`PySpam_System` is a plain C function, declared1161 :c:func:`PySpam_System` is also exported to other extension modules. 1162 1163 The function :c:func:`PySpam_System` is a plain C function, declared 1133 1164 ``static`` like everything else:: 1134 1165 … … 1139 1170 } 1140 1171 1141 The function :c func:`spam_system` is modified in a trivial way::1172 The function :c:func:`spam_system` is modified in a trivial way:: 1142 1173 1143 1174 static PyObject * … … 1180 1211 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System; 1181 1212 1182 /* Create a C Objectcontaining the API pointer array's address */1183 c_api_object = PyC Object_FromVoidPtr((void *)PySpam_API, NULL);1213 /* Create a Capsule containing the API pointer array's address */ 1214 c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL); 1184 1215 1185 1216 if (c_api_object != NULL) … … 1223 1254 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM]) 1224 1255 1225 /* Return -1 and set exception on error, 0 on success. */ 1256 /* Return -1 on error, 0 on success. 1257 * PyCapsule_Import will set an exception if there's an error. 1258 */ 1226 1259 static int 1227 1260 import_spam(void) 1228 1261 { 1229 PyObject *c_api_object; 1230 PyObject *module; 1231 1232 module = PyImport_ImportModule("spam"); 1233 if (module == NULL) 1234 return -1; 1235 1236 c_api_object = PyObject_GetAttrString(module, "_C_API"); 1237 if (c_api_object == NULL) { 1238 Py_DECREF(module); 1239 return -1; 1240 } 1241 if (PyCObject_Check(c_api_object)) 1242 PySpam_API = (void **)PyCObject_AsVoidPtr(c_api_object); 1243 1244 Py_DECREF(c_api_object); 1245 Py_DECREF(module); 1246 return 0; 1262 PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0); 1263 return (PySpam_API != NULL) ? 0 : -1; 1247 1264 } 1248 1265 … … 1256 1273 1257 1274 All that a client module must do in order to have access to the function 1258 :c func:`PySpam_System` is to call the function (or rather macro)1259 :c func:`import_spam` in its initialization function::1275 :c:func:`PySpam_System` is to call the function (or rather macro) 1276 :c:func:`import_spam` in its initialization function:: 1260 1277 1261 1278 PyMODINIT_FUNC … … 1276 1293 that is exported, so it has to be learned only once. 1277 1294 1278 Finally it should be mentioned that C Objects offer additional functionality,1295 Finally it should be mentioned that Capsules offer additional functionality, 1279 1296 which is especially useful for memory allocation and deallocation of the pointer 1280 stored in a C Object. The details are described in the Python/C API Reference1281 Manual in the section :ref:`c objects` and in the implementation of CObjects (files1282 :file:`Include/ cobject.h` and :file:`Objects/cobject.c` in the Python source1297 stored in a Capsule. The details are described in the Python/C API Reference 1298 Manual in the section :ref:`capsules` and in the implementation of Capsules (files 1299 :file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` in the Python source 1283 1300 code distribution). 1284 1301
Note:
See TracChangeset
for help on using the changeset viewer.