PageRenderTime 58ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/extending/extending.rst

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