blob: 433178ab64d8e537437203ef8171c0b6476ee908 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. highlightlang:: c
2
3
4.. _extending-intro:
5
6******************************
7Extending Python with C or C++
8******************************
9
10It is quite easy to add new built-in modules to Python, if you know how to
11program in C. Such :dfn:`extension modules` can do two things that can't be
12done directly in Python: they can implement new built-in object types, and they
13can call C library functions and system calls.
14
15To support extensions, the Python API (Application Programmers Interface)
16defines a set of functions, macros and variables that provide access to most
17aspects of the Python run-time system. The Python API is incorporated in a C
18source file by including the header ``"Python.h"``.
19
20The compilation of an extension module depends on its intended use as well as on
21your system setup; details are given in later chapters.
22
Benjamin Peterson63b55582015-01-05 14:38:46 -060023.. note::
Brett Cannon7f98a6c2009-09-17 03:39:33 +000024
Benjamin Peterson63b55582015-01-05 14:38:46 -060025 The C extension interface is specific to CPython, and extension modules do
26 not work on other Python implementations. In many cases, it is possible to
27 avoid writing C extensions and preserve portability to other implementations.
28 For example, if your use case is calling C library functions or system calls,
29 you should consider using the :mod:`ctypes` module or the `cffi
Sanyam Khurana338cd832018-01-20 05:55:37 +053030 <https://cffi.readthedocs.io/>`_ library rather than writing
31 custom C code.
Benjamin Peterson63b55582015-01-05 14:38:46 -060032 These modules let you write Python code to interface with C code and are more
33 portable between implementations of Python than writing and compiling a C
34 extension module.
Brett Cannon7f98a6c2009-09-17 03:39:33 +000035
Georg Brandl116aa622007-08-15 14:28:22 +000036
37.. _extending-simpleexample:
38
39A Simple Example
40================
41
42Let's create an extension module called ``spam`` (the favorite food of Monty
43Python fans...) and let's say we want to create a Python interface to the C
Emanuele Gaifascdfe9102017-11-24 09:49:57 +010044library function :c:func:`system` [#]_. This function takes a null-terminated
Georg Brandl116aa622007-08-15 14:28:22 +000045character string as argument and returns an integer. We want this function to
Serhiy Storchaka46936d52018-04-08 19:18:04 +030046be callable from Python as follows:
47
48.. code-block:: pycon
Georg Brandl116aa622007-08-15 14:28:22 +000049
50 >>> import spam
51 >>> status = spam.system("ls -l")
52
53Begin by creating a file :file:`spammodule.c`. (Historically, if a module is
54called ``spam``, the C file containing its implementation is called
55:file:`spammodule.c`; if the module name is very long, like ``spammify``, the
56module name can be just :file:`spammify.c`.)
57
Inada Naokic88fece2019-04-13 10:46:21 +090058The first two lines of our file can be::
Georg Brandl116aa622007-08-15 14:28:22 +000059
Inada Naokic88fece2019-04-13 10:46:21 +090060 #define PY_SSIZE_T_CLEAN
Georg Brandl116aa622007-08-15 14:28:22 +000061 #include <Python.h>
62
63which pulls in the Python API (you can add a comment describing the purpose of
64the module and a copyright notice if you like).
65
Georg Brandle720c0a2009-04-27 16:20:50 +000066.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000067
68 Since Python may define some pre-processor definitions which affect the standard
69 headers on some systems, you *must* include :file:`Python.h` before any standard
70 headers are included.
71
Inada Naokic88fece2019-04-13 10:46:21 +090072 It is recommended to always define ``PY_SSIZE_T_CLEAN`` before including
73 ``Python.h``. See :ref:`parsetuple` for a description of this macro.
74
Georg Brandl116aa622007-08-15 14:28:22 +000075All user-visible symbols defined by :file:`Python.h` have a prefix of ``Py`` or
76``PY``, except those defined in standard header files. For convenience, and
77since they are used extensively by the Python interpreter, ``"Python.h"``
78includes a few standard header files: ``<stdio.h>``, ``<string.h>``,
79``<errno.h>``, and ``<stdlib.h>``. If the latter header file does not exist on
Georg Brandl60203b42010-10-06 10:11:56 +000080your system, it declares the functions :c:func:`malloc`, :c:func:`free` and
81:c:func:`realloc` directly.
Georg Brandl116aa622007-08-15 14:28:22 +000082
83The next thing we add to our module file is the C function that will be called
84when the Python expression ``spam.system(string)`` is evaluated (we'll see
85shortly how it ends up being called)::
86
87 static PyObject *
88 spam_system(PyObject *self, PyObject *args)
89 {
90 const char *command;
91 int sts;
92
93 if (!PyArg_ParseTuple(args, "s", &command))
94 return NULL;
95 sts = system(command);
Georg Brandlc877a7c2010-11-26 11:55:48 +000096 return PyLong_FromLong(sts);
Georg Brandl116aa622007-08-15 14:28:22 +000097 }
98
99There is a straightforward translation from the argument list in Python (for
100example, the single expression ``"ls -l"``) to the arguments passed to the C
101function. The C function always has two arguments, conventionally named *self*
102and *args*.
103
Georg Brandl21dc5ba2009-07-11 10:43:08 +0000104The *self* argument points to the module object for module-level functions;
105for a method it would point to the object instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107The *args* argument will be a pointer to a Python tuple object containing the
108arguments. Each item of the tuple corresponds to an argument in the call's
109argument list. The arguments are Python objects --- in order to do anything
110with them in our C function we have to convert them to C values. The function
Georg Brandl60203b42010-10-06 10:11:56 +0000111:c:func:`PyArg_ParseTuple` in the Python API checks the argument types and
Georg Brandl116aa622007-08-15 14:28:22 +0000112converts them to C values. It uses a template string to determine the required
113types of the arguments as well as the types of the C variables into which to
114store the converted values. More about this later.
115
Georg Brandl60203b42010-10-06 10:11:56 +0000116:c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right
Georg Brandl116aa622007-08-15 14:28:22 +0000117type and its components have been stored in the variables whose addresses are
118passed. It returns false (zero) if an invalid argument list was passed. In the
119latter case it also raises an appropriate exception so the calling function can
120return *NULL* immediately (as we saw in the example).
121
122
123.. _extending-errors:
124
125Intermezzo: Errors and Exceptions
126=================================
127
128An important convention throughout the Python interpreter is the following: when
129a function fails, it should set an exception condition and return an error value
130(usually a *NULL* pointer). Exceptions are stored in a static global variable
131inside the interpreter; if this variable is *NULL* no exception has occurred. A
132second global variable stores the "associated value" of the exception (the
133second argument to :keyword:`raise`). A third variable contains the stack
134traceback in case the error originated in Python code. These three variables
135are the C equivalents of the result in Python of :meth:`sys.exc_info` (see the
136section on module :mod:`sys` in the Python Library Reference). It is important
137to know about them to understand how errors are passed around.
138
139The Python API defines a number of functions to set various types of exceptions.
140
Georg Brandl60203b42010-10-06 10:11:56 +0000141The most common one is :c:func:`PyErr_SetString`. Its arguments are an exception
Georg Brandl116aa622007-08-15 14:28:22 +0000142object and a C string. The exception object is usually a predefined object like
Georg Brandl60203b42010-10-06 10:11:56 +0000143:c:data:`PyExc_ZeroDivisionError`. The C string indicates the cause of the error
Georg Brandl116aa622007-08-15 14:28:22 +0000144and is converted to a Python string object and stored as the "associated value"
145of the exception.
146
Georg Brandl60203b42010-10-06 10:11:56 +0000147Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an
Georg Brandl116aa622007-08-15 14:28:22 +0000148exception argument and constructs the associated value by inspection of the
Georg Brandl60203b42010-10-06 10:11:56 +0000149global variable :c:data:`errno`. The most general function is
150:c:func:`PyErr_SetObject`, which takes two object arguments, the exception and
151its associated value. You don't need to :c:func:`Py_INCREF` the objects passed
Georg Brandl116aa622007-08-15 14:28:22 +0000152to any of these functions.
153
154You can test non-destructively whether an exception has been set with
Georg Brandl60203b42010-10-06 10:11:56 +0000155:c:func:`PyErr_Occurred`. This returns the current exception object, or *NULL*
Georg Brandl116aa622007-08-15 14:28:22 +0000156if no exception has occurred. You normally don't need to call
Georg Brandl60203b42010-10-06 10:11:56 +0000157:c:func:`PyErr_Occurred` to see whether an error occurred in a function call,
Georg Brandl116aa622007-08-15 14:28:22 +0000158since you should be able to tell from the return value.
159
160When a function *f* that calls another function *g* detects that the latter
161fails, *f* should itself return an error value (usually *NULL* or ``-1``). It
Georg Brandl60203b42010-10-06 10:11:56 +0000162should *not* call one of the :c:func:`PyErr_\*` functions --- one has already
Georg Brandl116aa622007-08-15 14:28:22 +0000163been called by *g*. *f*'s caller is then supposed to also return an error
Georg Brandl60203b42010-10-06 10:11:56 +0000164indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on
Georg Brandl116aa622007-08-15 14:28:22 +0000165--- the most detailed cause of the error was already reported by the function
166that first detected it. Once the error reaches the Python interpreter's main
167loop, this aborts the currently executing Python code and tries to find an
168exception handler specified by the Python programmer.
169
170(There are situations where a module can actually give a more detailed error
Georg Brandl60203b42010-10-06 10:11:56 +0000171message by calling another :c:func:`PyErr_\*` function, and in such cases it is
Georg Brandl116aa622007-08-15 14:28:22 +0000172fine to do so. As a general rule, however, this is not necessary, and can cause
173information about the cause of the error to be lost: most operations can fail
174for a variety of reasons.)
175
176To ignore an exception set by a function call that failed, the exception
Georg Brandl682d7e02010-10-06 10:26:05 +0000177condition must be cleared explicitly by calling :c:func:`PyErr_Clear`. The only
Georg Brandl60203b42010-10-06 10:11:56 +0000178time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the
Georg Brandl116aa622007-08-15 14:28:22 +0000179error on to the interpreter but wants to handle it completely by itself
180(possibly by trying something else, or pretending nothing went wrong).
181
Georg Brandl60203b42010-10-06 10:11:56 +0000182Every failing :c:func:`malloc` call must be turned into an exception --- the
183direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call
184:c:func:`PyErr_NoMemory` and return a failure indicator itself. All the
185object-creating functions (for example, :c:func:`PyLong_FromLong`) already do
186this, so this note is only relevant to those who call :c:func:`malloc` directly.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl60203b42010-10-06 10:11:56 +0000188Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and
Georg Brandl116aa622007-08-15 14:28:22 +0000189friends, functions that return an integer status usually return a positive value
190or zero for success and ``-1`` for failure, like Unix system calls.
191
Georg Brandl60203b42010-10-06 10:11:56 +0000192Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or
193:c:func:`Py_DECREF` calls for objects you have already created) when you return
Georg Brandl116aa622007-08-15 14:28:22 +0000194an error indicator!
195
196The choice of which exception to raise is entirely yours. There are predeclared
197C objects corresponding to all built-in Python exceptions, such as
Georg Brandl60203b42010-10-06 10:11:56 +0000198:c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you
199should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean
200that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`).
201If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple`
202function usually raises :c:data:`PyExc_TypeError`. If you have an argument whose
Georg Brandl116aa622007-08-15 14:28:22 +0000203value must be in a particular range or must satisfy other conditions,
Georg Brandl60203b42010-10-06 10:11:56 +0000204:c:data:`PyExc_ValueError` is appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206You can also define a new exception that is unique to your module. For this, you
207usually declare a static object variable at the beginning of your file::
208
209 static PyObject *SpamError;
210
Georg Brandl60203b42010-10-06 10:11:56 +0000211and initialize it in your module's initialization function (:c:func:`PyInit_spam`)
Georg Brandl116aa622007-08-15 14:28:22 +0000212with an exception object (leaving out the error checking for now)::
213
214 PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000215 PyInit_spam(void)
Georg Brandl116aa622007-08-15 14:28:22 +0000216 {
217 PyObject *m;
218
Martin v. Löwis1a214512008-06-11 05:26:20 +0000219 m = PyModule_Create(&spammodule);
Georg Brandl116aa622007-08-15 14:28:22 +0000220 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000221 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223 SpamError = PyErr_NewException("spam.error", NULL, NULL);
224 Py_INCREF(SpamError);
225 PyModule_AddObject(m, "error", SpamError);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000226 return m;
Georg Brandl116aa622007-08-15 14:28:22 +0000227 }
228
229Note that the Python name for the exception object is :exc:`spam.error`. The
Georg Brandl60203b42010-10-06 10:11:56 +0000230:c:func:`PyErr_NewException` function may create a class with the base class
Georg Brandl116aa622007-08-15 14:28:22 +0000231being :exc:`Exception` (unless another class is passed in instead of *NULL*),
232described in :ref:`bltin-exceptions`.
233
Georg Brandl60203b42010-10-06 10:11:56 +0000234Note also that the :c:data:`SpamError` variable retains a reference to the newly
Georg Brandl116aa622007-08-15 14:28:22 +0000235created exception class; this is intentional! Since the exception could be
236removed from the module by external code, an owned reference to the class is
Georg Brandl60203b42010-10-06 10:11:56 +0000237needed to ensure that it will not be discarded, causing :c:data:`SpamError` to
Georg Brandl116aa622007-08-15 14:28:22 +0000238become a dangling pointer. Should it become a dangling pointer, C code which
239raises the exception could cause a core dump or other unintended side effects.
240
Georg Brandl9c491c92010-08-02 20:21:21 +0000241We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this
Georg Brandl116aa622007-08-15 14:28:22 +0000242sample.
243
Georg Brandl9c491c92010-08-02 20:21:21 +0000244The :exc:`spam.error` exception can be raised in your extension module using a
Georg Brandl60203b42010-10-06 10:11:56 +0000245call to :c:func:`PyErr_SetString` as shown below::
Georg Brandl9c491c92010-08-02 20:21:21 +0000246
247 static PyObject *
248 spam_system(PyObject *self, PyObject *args)
249 {
250 const char *command;
251 int sts;
252
253 if (!PyArg_ParseTuple(args, "s", &command))
254 return NULL;
255 sts = system(command);
256 if (sts < 0) {
257 PyErr_SetString(SpamError, "System command failed");
258 return NULL;
259 }
260 return PyLong_FromLong(sts);
261 }
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263
264.. _backtoexample:
265
266Back to the Example
267===================
268
269Going back to our example function, you should now be able to understand this
270statement::
271
272 if (!PyArg_ParseTuple(args, "s", &command))
273 return NULL;
274
275It returns *NULL* (the error indicator for functions returning object pointers)
276if an error is detected in the argument list, relying on the exception set by
Georg Brandl60203b42010-10-06 10:11:56 +0000277:c:func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been
278copied to the local variable :c:data:`command`. This is a pointer assignment and
Georg Brandl116aa622007-08-15 14:28:22 +0000279you are not supposed to modify the string to which it points (so in Standard C,
Georg Brandl60203b42010-10-06 10:11:56 +0000280the variable :c:data:`command` should properly be declared as ``const char
Georg Brandl116aa622007-08-15 14:28:22 +0000281*command``).
282
Georg Brandl60203b42010-10-06 10:11:56 +0000283The next statement is a call to the Unix function :c:func:`system`, passing it
284the string we just got from :c:func:`PyArg_ParseTuple`::
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286 sts = system(command);
287
Georg Brandl60203b42010-10-06 10:11:56 +0000288Our :func:`spam.system` function must return the value of :c:data:`sts` as a
Georg Brandlc877a7c2010-11-26 11:55:48 +0000289Python object. This is done using the function :c:func:`PyLong_FromLong`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Georg Brandlc877a7c2010-11-26 11:55:48 +0000291 return PyLong_FromLong(sts);
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293In this case, it will return an integer object. (Yes, even integers are objects
294on the heap in Python!)
295
296If you have a C function that returns no useful argument (a function returning
Georg Brandl60203b42010-10-06 10:11:56 +0000297:c:type:`void`), the corresponding Python function must return ``None``. You
298need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE`
Georg Brandl116aa622007-08-15 14:28:22 +0000299macro)::
300
301 Py_INCREF(Py_None);
302 return Py_None;
303
Georg Brandl60203b42010-10-06 10:11:56 +0000304:c:data:`Py_None` is the C name for the special Python object ``None``. It is a
Georg Brandl116aa622007-08-15 14:28:22 +0000305genuine Python object rather than a *NULL* pointer, which means "error" in most
306contexts, as we have seen.
307
308
309.. _methodtable:
310
311The Module's Method Table and Initialization Function
312=====================================================
313
Georg Brandl60203b42010-10-06 10:11:56 +0000314I promised to show how :c:func:`spam_system` is called from Python programs.
Georg Brandl116aa622007-08-15 14:28:22 +0000315First, we need to list its name and address in a "method table"::
316
317 static PyMethodDef SpamMethods[] = {
318 ...
319 {"system", spam_system, METH_VARARGS,
320 "Execute a shell command."},
321 ...
322 {NULL, NULL, 0, NULL} /* Sentinel */
323 };
324
325Note the third entry (``METH_VARARGS``). This is a flag telling the interpreter
326the calling convention to be used for the C function. It should normally always
327be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means
Georg Brandl60203b42010-10-06 10:11:56 +0000328that an obsolete variant of :c:func:`PyArg_ParseTuple` is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330When using only ``METH_VARARGS``, the function should expect the Python-level
331parameters to be passed in as a tuple acceptable for parsing via
Georg Brandl60203b42010-10-06 10:11:56 +0000332:c:func:`PyArg_ParseTuple`; more information on this function is provided below.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334The :const:`METH_KEYWORDS` bit may be set in the third field if keyword
335arguments should be passed to the function. In this case, the C function should
Eli Bendersky44fb6132012-02-11 10:27:31 +0200336accept a third ``PyObject *`` parameter which will be a dictionary of keywords.
Georg Brandl60203b42010-10-06 10:11:56 +0000337Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a
Georg Brandl116aa622007-08-15 14:28:22 +0000338function.
339
Martin v. Löwis1a214512008-06-11 05:26:20 +0000340The method table must be referenced in the module definition structure::
341
Benjamin Peterson3851d122008-10-20 21:04:06 +0000342 static struct PyModuleDef spammodule = {
Sergey Fedoseevd9a2b992017-08-30 19:50:40 +0500343 PyModuleDef_HEAD_INIT,
344 "spam", /* name of module */
345 spam_doc, /* module documentation, may be NULL */
346 -1, /* size of per-interpreter state of the module,
347 or -1 if the module keeps state in global variables. */
348 SpamMethods
Martin v. Löwis1a214512008-06-11 05:26:20 +0000349 };
350
351This structure, in turn, must be passed to the interpreter in the module's
Georg Brandl116aa622007-08-15 14:28:22 +0000352initialization function. The initialization function must be named
Georg Brandl60203b42010-10-06 10:11:56 +0000353:c:func:`PyInit_name`, where *name* is the name of the module, and should be the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000354only non-\ ``static`` item defined in the module file::
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356 PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000357 PyInit_spam(void)
Georg Brandl116aa622007-08-15 14:28:22 +0000358 {
Martin v. Löwis1a214512008-06-11 05:26:20 +0000359 return PyModule_Create(&spammodule);
Georg Brandl116aa622007-08-15 14:28:22 +0000360 }
361
Benjamin Peterson71e30a02008-12-24 16:27:25 +0000362Note that PyMODINIT_FUNC declares the function as ``PyObject *`` return type,
363declares any special linkage declarations required by the platform, and for C++
Georg Brandl116aa622007-08-15 14:28:22 +0000364declares the function as ``extern "C"``.
365
366When the Python program imports module :mod:`spam` for the first time,
Georg Brandl60203b42010-10-06 10:11:56 +0000367:c:func:`PyInit_spam` is called. (See below for comments about embedding Python.)
368It calls :c:func:`PyModule_Create`, which returns a module object, and
Georg Brandl116aa622007-08-15 14:28:22 +0000369inserts built-in function objects into the newly created module based upon the
Georg Brandl60203b42010-10-06 10:11:56 +0000370table (an array of :c:type:`PyMethodDef` structures) found in the module definition.
371:c:func:`PyModule_Create` returns a pointer to the module object
Martin v. Löwis1a214512008-06-11 05:26:20 +0000372that it creates. It may abort with a fatal error for
Georg Brandl116aa622007-08-15 14:28:22 +0000373certain errors, or return *NULL* if the module could not be initialized
Martin v. Löwis1a214512008-06-11 05:26:20 +0000374satisfactorily. The init function must return the module object to its caller,
375so that it then gets inserted into ``sys.modules``.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Georg Brandl60203b42010-10-06 10:11:56 +0000377When embedding Python, the :c:func:`PyInit_spam` function is not called
378automatically unless there's an entry in the :c:data:`PyImport_Inittab` table.
379To add the module to the initialization table, use :c:func:`PyImport_AppendInittab`,
Martin v. Löwis1a214512008-06-11 05:26:20 +0000380optionally followed by an import of the module::
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382 int
383 main(int argc, char *argv[])
384 {
Victor Stinner25e014b2014-08-01 12:28:49 +0200385 wchar_t *program = Py_DecodeLocale(argv[0], NULL);
386 if (program == NULL) {
387 fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
388 exit(1);
389 }
390
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000391 /* Add a built-in module, before Py_Initialize */
Martin v. Löwis1a214512008-06-11 05:26:20 +0000392 PyImport_AppendInittab("spam", PyInit_spam);
393
Georg Brandl116aa622007-08-15 14:28:22 +0000394 /* Pass argv[0] to the Python interpreter */
Victor Stinner25e014b2014-08-01 12:28:49 +0200395 Py_SetProgramName(program);
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397 /* Initialize the Python interpreter. Required. */
398 Py_Initialize();
399
Martin v. Löwis1a214512008-06-11 05:26:20 +0000400 /* Optionally import the module; alternatively,
401 import can be deferred until the embedded script
402 imports it. */
403 PyImport_ImportModule("spam");
Georg Brandl116aa622007-08-15 14:28:22 +0000404
Georg Brandl49c6fc92013-10-06 13:14:10 +0200405 ...
406
Victor Stinner25e014b2014-08-01 12:28:49 +0200407 PyMem_RawFree(program);
408 return 0;
409 }
410
Georg Brandl116aa622007-08-15 14:28:22 +0000411.. note::
412
413 Removing entries from ``sys.modules`` or importing compiled modules into
Georg Brandl60203b42010-10-06 10:11:56 +0000414 multiple interpreters within a process (or following a :c:func:`fork` without an
415 intervening :c:func:`exec`) can create problems for some extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000416 Extension module authors should exercise caution when initializing internal data
417 structures.
418
419A more substantial example module is included in the Python source distribution
420as :file:`Modules/xxmodule.c`. This file may be used as a template or simply
Benjamin Peterson2614cda2010-03-21 22:36:19 +0000421read as an example.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Nick Coghlan2ab5b092015-07-03 19:49:15 +1000423.. note::
424
425 Unlike our ``spam`` example, ``xxmodule`` uses *multi-phase initialization*
426 (new in Python 3.5), where a PyModuleDef structure is returned from
427 ``PyInit_spam``, and creation of the module is left to the import machinery.
428 For details on multi-phase initialization, see :PEP:`489`.
429
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431.. _compilation:
432
433Compilation and Linkage
434=======================
435
436There are two more things to do before you can use your new extension: compiling
437and linking it with the Python system. If you use dynamic loading, the details
438may depend on the style of dynamic loading your system uses; see the chapters
439about building extension modules (chapter :ref:`building`) and additional
440information that pertains only to building on Windows (chapter
441:ref:`building-on-windows`) for more information about this.
442
443If you can't use dynamic loading, or if you want to make your module a permanent
444part of the Python interpreter, you will have to change the configuration setup
445and rebuild the interpreter. Luckily, this is very simple on Unix: just place
446your file (:file:`spammodule.c` for example) in the :file:`Modules/` directory
447of an unpacked source distribution, add a line to the file
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300448:file:`Modules/Setup.local` describing your file:
449
450.. code-block:: sh
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452 spam spammodule.o
453
454and rebuild the interpreter by running :program:`make` in the toplevel
455directory. You can also run :program:`make` in the :file:`Modules/`
456subdirectory, but then you must first rebuild :file:`Makefile` there by running
457':program:`make` Makefile'. (This is necessary each time you change the
458:file:`Setup` file.)
459
460If your module requires additional libraries to link with, these can be listed
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300461on the line in the configuration file as well, for instance:
462
463.. code-block:: sh
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465 spam spammodule.o -lX11
466
467
468.. _callingpython:
469
470Calling Python Functions from C
471===============================
472
473So far we have concentrated on making C functions callable from Python. The
474reverse is also useful: calling Python functions from C. This is especially the
475case for libraries that support so-called "callback" functions. If a C
476interface makes use of callbacks, the equivalent Python often needs to provide a
477callback mechanism to the Python programmer; the implementation will require
478calling the Python callback functions from a C callback. Other uses are also
479imaginable.
480
481Fortunately, the Python interpreter is easily called recursively, and there is a
482standard interface to call a Python function. (I won't dwell on how to call the
483Python parser with a particular string as input --- if you're interested, have a
484look at the implementation of the :option:`-c` command line option in
Georg Brandl22291c52007-09-06 14:49:02 +0000485:file:`Modules/main.c` from the Python source code.)
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487Calling a Python function is easy. First, the Python program must somehow pass
488you the Python function object. You should provide a function (or some other
489interface) to do this. When this function is called, save a pointer to the
Georg Brandl60203b42010-10-06 10:11:56 +0000490Python function object (be careful to :c:func:`Py_INCREF` it!) in a global
Georg Brandl116aa622007-08-15 14:28:22 +0000491variable --- or wherever you see fit. For example, the following function might
492be part of a module definition::
493
494 static PyObject *my_callback = NULL;
495
496 static PyObject *
497 my_set_callback(PyObject *dummy, PyObject *args)
498 {
499 PyObject *result = NULL;
500 PyObject *temp;
501
502 if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
503 if (!PyCallable_Check(temp)) {
504 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
505 return NULL;
506 }
507 Py_XINCREF(temp); /* Add a reference to new callback */
508 Py_XDECREF(my_callback); /* Dispose of previous callback */
509 my_callback = temp; /* Remember new callback */
510 /* Boilerplate to return "None" */
511 Py_INCREF(Py_None);
512 result = Py_None;
513 }
514 return result;
515 }
516
517This function must be registered with the interpreter using the
518:const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The
Georg Brandl60203b42010-10-06 10:11:56 +0000519:c:func:`PyArg_ParseTuple` function and its arguments are documented in section
Georg Brandl116aa622007-08-15 14:28:22 +0000520:ref:`parsetuple`.
521
Georg Brandl60203b42010-10-06 10:11:56 +0000522The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the
Georg Brandl116aa622007-08-15 14:28:22 +0000523reference count of an object and are safe in the presence of *NULL* pointers
524(but note that *temp* will not be *NULL* in this context). More info on them
525in section :ref:`refcounts`.
526
Benjamin Petersond23f8222009-04-05 19:13:16 +0000527.. index:: single: PyObject_CallObject()
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529Later, when it is time to call the function, you call the C function
Georg Brandl60203b42010-10-06 10:11:56 +0000530:c:func:`PyObject_CallObject`. This function has two arguments, both pointers to
Georg Brandl116aa622007-08-15 14:28:22 +0000531arbitrary Python objects: the Python function, and the argument list. The
532argument list must always be a tuple object, whose length is the number of
Georg Brandl48310cd2009-01-03 21:18:54 +0000533arguments. To call the Python function with no arguments, pass in NULL, or
Christian Heimesd8654cf2007-12-02 15:22:16 +0000534an empty tuple; to call it with one argument, pass a singleton tuple.
Georg Brandl60203b42010-10-06 10:11:56 +0000535:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero
Christian Heimesd8654cf2007-12-02 15:22:16 +0000536or more format codes between parentheses. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538 int arg;
539 PyObject *arglist;
540 PyObject *result;
541 ...
542 arg = 123;
543 ...
544 /* Time to call the callback */
545 arglist = Py_BuildValue("(i)", arg);
Benjamin Petersond23f8222009-04-05 19:13:16 +0000546 result = PyObject_CallObject(my_callback, arglist);
Georg Brandl116aa622007-08-15 14:28:22 +0000547 Py_DECREF(arglist);
548
Georg Brandl60203b42010-10-06 10:11:56 +0000549:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return
550value of the Python function. :c:func:`PyObject_CallObject` is
Georg Brandl116aa622007-08-15 14:28:22 +0000551"reference-count-neutral" with respect to its arguments. In the example a new
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200552tuple was created to serve as the argument list, which is
553:c:func:`Py_DECREF`\ -ed immediately after the :c:func:`PyObject_CallObject`
554call.
Georg Brandl116aa622007-08-15 14:28:22 +0000555
Georg Brandl60203b42010-10-06 10:11:56 +0000556The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand
Georg Brandl116aa622007-08-15 14:28:22 +0000557new object, or it is an existing object whose reference count has been
558incremented. So, unless you want to save it in a global variable, you should
Georg Brandl60203b42010-10-06 10:11:56 +0000559somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not
Georg Brandl116aa622007-08-15 14:28:22 +0000560interested in its value.
561
562Before you do this, however, it is important to check that the return value
563isn't *NULL*. If it is, the Python function terminated by raising an exception.
Georg Brandl60203b42010-10-06 10:11:56 +0000564If the C code that called :c:func:`PyObject_CallObject` is called from Python, it
Georg Brandl116aa622007-08-15 14:28:22 +0000565should now return an error indication to its Python caller, so the interpreter
566can print a stack trace, or the calling Python code can handle the exception.
567If this is not possible or desirable, the exception should be cleared by calling
Georg Brandl60203b42010-10-06 10:11:56 +0000568:c:func:`PyErr_Clear`. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000569
570 if (result == NULL)
571 return NULL; /* Pass error back */
572 ...use result...
Georg Brandl48310cd2009-01-03 21:18:54 +0000573 Py_DECREF(result);
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575Depending on the desired interface to the Python callback function, you may also
Georg Brandl60203b42010-10-06 10:11:56 +0000576have to provide an argument list to :c:func:`PyObject_CallObject`. In some cases
Georg Brandl116aa622007-08-15 14:28:22 +0000577the argument list is also provided by the Python program, through the same
578interface that specified the callback function. It can then be saved and used
579in the same manner as the function object. In other cases, you may have to
580construct a new tuple to pass as the argument list. The simplest way to do this
Georg Brandl60203b42010-10-06 10:11:56 +0000581is to call :c:func:`Py_BuildValue`. For example, if you want to pass an integral
Georg Brandl116aa622007-08-15 14:28:22 +0000582event code, you might use the following code::
583
584 PyObject *arglist;
585 ...
586 arglist = Py_BuildValue("(l)", eventcode);
Benjamin Petersond23f8222009-04-05 19:13:16 +0000587 result = PyObject_CallObject(my_callback, arglist);
Georg Brandl116aa622007-08-15 14:28:22 +0000588 Py_DECREF(arglist);
589 if (result == NULL)
590 return NULL; /* Pass error back */
591 /* Here maybe use the result */
592 Py_DECREF(result);
593
594Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before
Christian Heimesd8654cf2007-12-02 15:22:16 +0000595the error check! Also note that strictly speaking this code is not complete:
Georg Brandl60203b42010-10-06 10:11:56 +0000596:c:func:`Py_BuildValue` may run out of memory, and this should be checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000597
Georg Brandl48310cd2009-01-03 21:18:54 +0000598You may also call a function with keyword arguments by using
Georg Brandl60203b42010-10-06 10:11:56 +0000599:c:func:`PyObject_Call`, which supports arguments and keyword arguments. As in
600the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::
Christian Heimesd8654cf2007-12-02 15:22:16 +0000601
602 PyObject *dict;
603 ...
604 dict = Py_BuildValue("{s:i}", "name", val);
Benjamin Petersond23f8222009-04-05 19:13:16 +0000605 result = PyObject_Call(my_callback, NULL, dict);
Christian Heimesd8654cf2007-12-02 15:22:16 +0000606 Py_DECREF(dict);
607 if (result == NULL)
608 return NULL; /* Pass error back */
609 /* Here maybe use the result */
610 Py_DECREF(result);
Georg Brandl116aa622007-08-15 14:28:22 +0000611
Benjamin Petersond23f8222009-04-05 19:13:16 +0000612
Georg Brandl116aa622007-08-15 14:28:22 +0000613.. _parsetuple:
614
615Extracting Parameters in Extension Functions
616============================================
617
618.. index:: single: PyArg_ParseTuple()
619
Georg Brandl60203b42010-10-06 10:11:56 +0000620The :c:func:`PyArg_ParseTuple` function is declared as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000621
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300622 int PyArg_ParseTuple(PyObject *arg, const char *format, ...);
Georg Brandl116aa622007-08-15 14:28:22 +0000623
624The *arg* argument must be a tuple object containing an argument list passed
625from Python to a C function. The *format* argument must be a format string,
626whose syntax is explained in :ref:`arg-parsing` in the Python/C API Reference
627Manual. The remaining arguments must be addresses of variables whose type is
628determined by the format string.
629
Georg Brandl60203b42010-10-06 10:11:56 +0000630Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have
Georg Brandl116aa622007-08-15 14:28:22 +0000631the required types, it cannot check the validity of the addresses of C variables
632passed to the call: if you make mistakes there, your code will probably crash or
633at least overwrite random bits in memory. So be careful!
634
635Note that any Python object references which are provided to the caller are
636*borrowed* references; do not decrement their reference count!
637
638Some example calls::
639
Gregory P. Smith02c3b5c2008-11-23 23:49:16 +0000640 #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */
641 #include <Python.h>
642
643::
644
Georg Brandl116aa622007-08-15 14:28:22 +0000645 int ok;
646 int i, j;
647 long k, l;
648 const char *s;
Gregory P. Smith02c3b5c2008-11-23 23:49:16 +0000649 Py_ssize_t size;
Georg Brandl116aa622007-08-15 14:28:22 +0000650
651 ok = PyArg_ParseTuple(args, ""); /* No arguments */
652 /* Python call: f() */
653
654::
655
656 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
657 /* Possible Python call: f('whoops!') */
658
659::
660
661 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
662 /* Possible Python call: f(1, 2, 'three') */
663
664::
665
666 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
667 /* A pair of ints and a string, whose size is also returned */
668 /* Possible Python call: f((1, 2), 'three') */
669
670::
671
672 {
673 const char *file;
674 const char *mode = "r";
675 int bufsize = 0;
676 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
677 /* A string, and optionally another string and an integer */
678 /* Possible Python calls:
679 f('spam')
680 f('spam', 'w')
681 f('spam', 'wb', 100000) */
682 }
683
684::
685
686 {
687 int left, top, right, bottom, h, v;
688 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
689 &left, &top, &right, &bottom, &h, &v);
690 /* A rectangle and a point */
691 /* Possible Python call:
692 f(((0, 0), (400, 300)), (10, 10)) */
693 }
694
695::
696
697 {
698 Py_complex c;
699 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
700 /* a complex, also providing a function name for errors */
701 /* Possible Python call: myfunction(1+2j) */
702 }
703
704
705.. _parsetupleandkeywords:
706
707Keyword Parameters for Extension Functions
708==========================================
709
710.. index:: single: PyArg_ParseTupleAndKeywords()
711
Georg Brandl60203b42010-10-06 10:11:56 +0000712The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000713
714 int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300715 const char *format, char *kwlist[], ...);
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717The *arg* and *format* parameters are identical to those of the
Georg Brandl60203b42010-10-06 10:11:56 +0000718:c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of
Georg Brandl116aa622007-08-15 14:28:22 +0000719keywords received as the third parameter from the Python runtime. The *kwlist*
720parameter is a *NULL*-terminated list of strings which identify the parameters;
721the names are matched with the type information from *format* from left to
Georg Brandl60203b42010-10-06 10:11:56 +0000722right. On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise
Georg Brandl116aa622007-08-15 14:28:22 +0000723it returns false and raises an appropriate exception.
724
725.. note::
726
727 Nested tuples cannot be parsed when using keyword arguments! Keyword parameters
728 passed in which are not present in the *kwlist* will cause :exc:`TypeError` to
729 be raised.
730
731.. index:: single: Philbrick, Geoff
732
733Here is an example module which uses keywords, based on an example by Geoff
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000734Philbrick (philbrick@hks.com)::
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Inada Naokic88fece2019-04-13 10:46:21 +0900736 #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */
737 #include <Python.h>
Georg Brandl116aa622007-08-15 14:28:22 +0000738
739 static PyObject *
740 keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
Georg Brandl48310cd2009-01-03 21:18:54 +0000741 {
Georg Brandl116aa622007-08-15 14:28:22 +0000742 int voltage;
Serhiy Storchaka84b8e922017-03-30 10:01:03 +0300743 const char *state = "a stiff";
744 const char *action = "voom";
745 const char *type = "Norwegian Blue";
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
748
Georg Brandl48310cd2009-01-03 21:18:54 +0000749 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
Georg Brandl116aa622007-08-15 14:28:22 +0000750 &voltage, &state, &action, &type))
Georg Brandl48310cd2009-01-03 21:18:54 +0000751 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandl48310cd2009-01-03 21:18:54 +0000753 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
Georg Brandl116aa622007-08-15 14:28:22 +0000754 action, voltage);
755 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
756
Georg Brandla072de12013-10-06 20:46:08 +0200757 Py_RETURN_NONE;
Georg Brandl116aa622007-08-15 14:28:22 +0000758 }
759
760 static PyMethodDef keywdarg_methods[] = {
761 /* The cast of the function is necessary since PyCFunction values
762 * only take two PyObject* parameters, and keywdarg_parrot() takes
763 * three.
764 */
Serhiy Storchaka62be7422018-11-27 13:27:31 +0200765 {"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
Georg Brandl116aa622007-08-15 14:28:22 +0000766 "Print a lovely skit to standard output."},
767 {NULL, NULL, 0, NULL} /* sentinel */
768 };
769
Eli Bendersky8f773492012-08-15 14:49:49 +0300770 static struct PyModuleDef keywdargmodule = {
771 PyModuleDef_HEAD_INIT,
772 "keywdarg",
773 NULL,
774 -1,
775 keywdarg_methods
776 };
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Eli Bendersky8f773492012-08-15 14:49:49 +0300778 PyMODINIT_FUNC
779 PyInit_keywdarg(void)
Georg Brandl116aa622007-08-15 14:28:22 +0000780 {
Eli Bendersky8f773492012-08-15 14:49:49 +0300781 return PyModule_Create(&keywdargmodule);
Georg Brandl116aa622007-08-15 14:28:22 +0000782 }
783
784
785.. _buildvalue:
786
787Building Arbitrary Values
788=========================
789
Georg Brandl60203b42010-10-06 10:11:56 +0000790This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is declared
Georg Brandl116aa622007-08-15 14:28:22 +0000791as follows::
792
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300793 PyObject *Py_BuildValue(const char *format, ...);
Georg Brandl116aa622007-08-15 14:28:22 +0000794
795It recognizes a set of format units similar to the ones recognized by
Georg Brandl60203b42010-10-06 10:11:56 +0000796:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function,
Georg Brandl116aa622007-08-15 14:28:22 +0000797not output) must not be pointers, just values. It returns a new Python object,
798suitable for returning from a C function called from Python.
799
Georg Brandl60203b42010-10-06 10:11:56 +0000800One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its
Georg Brandl116aa622007-08-15 14:28:22 +0000801first argument to be a tuple (since Python argument lists are always represented
Georg Brandl60203b42010-10-06 10:11:56 +0000802as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple. It
Georg Brandl116aa622007-08-15 14:28:22 +0000803builds a tuple only if its format string contains two or more format units. If
804the format string is empty, it returns ``None``; if it contains exactly one
805format unit, it returns whatever object is described by that format unit. To
806force it to return a tuple of size 0 or one, parenthesize the format string.
807
Martin Panter1050d2d2016-07-26 11:18:21 +0200808Examples (to the left the call, to the right the resulting Python value):
809
810.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000811
812 Py_BuildValue("") None
813 Py_BuildValue("i", 123) 123
814 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
815 Py_BuildValue("s", "hello") 'hello'
816 Py_BuildValue("y", "hello") b'hello'
817 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
818 Py_BuildValue("s#", "hello", 4) 'hell'
819 Py_BuildValue("y#", "hello", 4) b'hell'
820 Py_BuildValue("()") ()
821 Py_BuildValue("(i)", 123) (123,)
822 Py_BuildValue("(ii)", 123, 456) (123, 456)
823 Py_BuildValue("(i,i)", 123, 456) (123, 456)
824 Py_BuildValue("[i,i]", 123, 456) [123, 456]
825 Py_BuildValue("{s:i,s:i}",
826 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
827 Py_BuildValue("((ii)(ii)) (ii)",
828 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
829
830
831.. _refcounts:
832
833Reference Counts
834================
835
836In languages like C or C++, the programmer is responsible for dynamic allocation
837and deallocation of memory on the heap. In C, this is done using the functions
Georg Brandl60203b42010-10-06 10:11:56 +0000838:c:func:`malloc` and :c:func:`free`. In C++, the operators ``new`` and
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000839``delete`` are used with essentially the same meaning and we'll restrict
Georg Brandl116aa622007-08-15 14:28:22 +0000840the following discussion to the C case.
841
Georg Brandl60203b42010-10-06 10:11:56 +0000842Every block of memory allocated with :c:func:`malloc` should eventually be
843returned to the pool of available memory by exactly one call to :c:func:`free`.
844It is important to call :c:func:`free` at the right time. If a block's address
845is forgotten but :c:func:`free` is not called for it, the memory it occupies
Georg Brandl116aa622007-08-15 14:28:22 +0000846cannot be reused until the program terminates. This is called a :dfn:`memory
Georg Brandl60203b42010-10-06 10:11:56 +0000847leak`. On the other hand, if a program calls :c:func:`free` for a block and then
Georg Brandl116aa622007-08-15 14:28:22 +0000848continues to use the block, it creates a conflict with re-use of the block
Georg Brandl60203b42010-10-06 10:11:56 +0000849through another :c:func:`malloc` call. This is called :dfn:`using freed memory`.
Georg Brandl116aa622007-08-15 14:28:22 +0000850It has the same bad consequences as referencing uninitialized data --- core
851dumps, wrong results, mysterious crashes.
852
853Common causes of memory leaks are unusual paths through the code. For instance,
854a function may allocate a block of memory, do some calculation, and then free
855the block again. Now a change in the requirements for the function may add a
856test to the calculation that detects an error condition and can return
857prematurely from the function. It's easy to forget to free the allocated memory
858block when taking this premature exit, especially when it is added later to the
859code. Such leaks, once introduced, often go undetected for a long time: the
860error exit is taken only in a small fraction of all calls, and most modern
861machines have plenty of virtual memory, so the leak only becomes apparent in a
862long-running process that uses the leaking function frequently. Therefore, it's
863important to prevent leaks from happening by having a coding convention or
864strategy that minimizes this kind of errors.
865
Georg Brandl60203b42010-10-06 10:11:56 +0000866Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a
Georg Brandl116aa622007-08-15 14:28:22 +0000867strategy to avoid memory leaks as well as the use of freed memory. The chosen
868method is called :dfn:`reference counting`. The principle is simple: every
869object contains a counter, which is incremented when a reference to the object
870is stored somewhere, and which is decremented when a reference to it is deleted.
871When the counter reaches zero, the last reference to the object has been deleted
872and the object is freed.
873
874An alternative strategy is called :dfn:`automatic garbage collection`.
875(Sometimes, reference counting is also referred to as a garbage collection
876strategy, hence my use of "automatic" to distinguish the two.) The big
877advantage of automatic garbage collection is that the user doesn't need to call
Georg Brandl60203b42010-10-06 10:11:56 +0000878:c:func:`free` explicitly. (Another claimed advantage is an improvement in speed
Georg Brandl116aa622007-08-15 14:28:22 +0000879or memory usage --- this is no hard fact however.) The disadvantage is that for
880C, there is no truly portable automatic garbage collector, while reference
Georg Brandl60203b42010-10-06 10:11:56 +0000881counting can be implemented portably (as long as the functions :c:func:`malloc`
882and :c:func:`free` are available --- which the C Standard guarantees). Maybe some
Georg Brandl116aa622007-08-15 14:28:22 +0000883day a sufficiently portable automatic garbage collector will be available for C.
884Until then, we'll have to live with reference counts.
885
886While Python uses the traditional reference counting implementation, it also
887offers a cycle detector that works to detect reference cycles. This allows
888applications to not worry about creating direct or indirect circular references;
889these are the weakness of garbage collection implemented using only reference
890counting. Reference cycles consist of objects which contain (possibly indirect)
891references to themselves, so that each object in the cycle has a reference count
892which is non-zero. Typical reference counting implementations are not able to
893reclaim the memory belonging to any objects in a reference cycle, or referenced
894from the objects in the cycle, even though there are no further references to
895the cycle itself.
896
Georg Brandla4c8c472014-10-31 10:38:49 +0100897The cycle detector is able to detect garbage cycles and can reclaim them.
898The :mod:`gc` module exposes a way to run the detector (the
Serhiy Storchaka0b68a2d2013-10-09 13:26:17 +0300899:func:`~gc.collect` function), as well as configuration
Georg Brandl116aa622007-08-15 14:28:22 +0000900interfaces and the ability to disable the detector at runtime. The cycle
901detector is considered an optional component; though it is included by default,
Martin Panter5c679332016-10-30 04:20:17 +0000902it can be disabled at build time using the :option:`!--without-cycle-gc` option
Georg Brandlf6945182008-02-01 11:56:49 +0000903to the :program:`configure` script on Unix platforms (including Mac OS X). If
904the cycle detector is disabled in this way, the :mod:`gc` module will not be
905available.
Georg Brandl116aa622007-08-15 14:28:22 +0000906
907
908.. _refcountsinpython:
909
910Reference Counting in Python
911----------------------------
912
913There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the
Georg Brandl60203b42010-10-06 10:11:56 +0000914incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also
Georg Brandl116aa622007-08-15 14:28:22 +0000915frees the object when the count reaches zero. For flexibility, it doesn't call
Georg Brandl60203b42010-10-06 10:11:56 +0000916:c:func:`free` directly --- rather, it makes a call through a function pointer in
Georg Brandl116aa622007-08-15 14:28:22 +0000917the object's :dfn:`type object`. For this purpose (and others), every object
918also contains a pointer to its type object.
919
920The big question now remains: when to use ``Py_INCREF(x)`` and ``Py_DECREF(x)``?
921Let's first introduce some terms. Nobody "owns" an object; however, you can
922:dfn:`own a reference` to an object. An object's reference count is now defined
923as the number of owned references to it. The owner of a reference is
Georg Brandl60203b42010-10-06 10:11:56 +0000924responsible for calling :c:func:`Py_DECREF` when the reference is no longer
Georg Brandl116aa622007-08-15 14:28:22 +0000925needed. Ownership of a reference can be transferred. There are three ways to
Georg Brandl60203b42010-10-06 10:11:56 +0000926dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`.
Georg Brandl116aa622007-08-15 14:28:22 +0000927Forgetting to dispose of an owned reference creates a memory leak.
928
929It is also possible to :dfn:`borrow` [#]_ a reference to an object. The
Georg Brandl60203b42010-10-06 10:11:56 +0000930borrower of a reference should not call :c:func:`Py_DECREF`. The borrower must
Georg Brandl116aa622007-08-15 14:28:22 +0000931not hold on to the object longer than the owner from which it was borrowed.
932Using a borrowed reference after the owner has disposed of it risks using freed
Emanuele Gaifascdfe9102017-11-24 09:49:57 +0100933memory and should be avoided completely [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935The advantage of borrowing over owning a reference is that you don't need to
936take care of disposing of the reference on all possible paths through the code
937--- in other words, with a borrowed reference you don't run the risk of leaking
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000938when a premature exit is taken. The disadvantage of borrowing over owning is
Georg Brandl116aa622007-08-15 14:28:22 +0000939that there are some subtle situations where in seemingly correct code a borrowed
940reference can be used after the owner from which it was borrowed has in fact
941disposed of it.
942
943A borrowed reference can be changed into an owned reference by calling
Georg Brandl60203b42010-10-06 10:11:56 +0000944:c:func:`Py_INCREF`. This does not affect the status of the owner from which the
Georg Brandl116aa622007-08-15 14:28:22 +0000945reference was borrowed --- it creates a new owned reference, and gives full
946owner responsibilities (the new owner must dispose of the reference properly, as
947well as the previous owner).
948
949
950.. _ownershiprules:
951
952Ownership Rules
953---------------
954
955Whenever an object reference is passed into or out of a function, it is part of
956the function's interface specification whether ownership is transferred with the
957reference or not.
958
959Most functions that return a reference to an object pass on ownership with the
960reference. In particular, all functions whose function it is to create a new
Georg Brandl60203b42010-10-06 10:11:56 +0000961object, such as :c:func:`PyLong_FromLong` and :c:func:`Py_BuildValue`, pass
Georg Brandl116aa622007-08-15 14:28:22 +0000962ownership to the receiver. Even if the object is not actually new, you still
963receive ownership of a new reference to that object. For instance,
Georg Brandl60203b42010-10-06 10:11:56 +0000964:c:func:`PyLong_FromLong` maintains a cache of popular values and can return a
Georg Brandl116aa622007-08-15 14:28:22 +0000965reference to a cached item.
966
967Many functions that extract objects from other objects also transfer ownership
Georg Brandl60203b42010-10-06 10:11:56 +0000968with the reference, for instance :c:func:`PyObject_GetAttrString`. The picture
Georg Brandl116aa622007-08-15 14:28:22 +0000969is less clear, here, however, since a few common routines are exceptions:
Georg Brandl60203b42010-10-06 10:11:56 +0000970:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and
971:c:func:`PyDict_GetItemString` all return references that you borrow from the
Georg Brandl116aa622007-08-15 14:28:22 +0000972tuple, list or dictionary.
973
Georg Brandl60203b42010-10-06 10:11:56 +0000974The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even
Georg Brandl116aa622007-08-15 14:28:22 +0000975though it may actually create the object it returns: this is possible because an
976owned reference to the object is stored in ``sys.modules``.
977
978When you pass an object reference into another function, in general, the
979function borrows the reference from you --- if it needs to store it, it will use
Georg Brandl60203b42010-10-06 10:11:56 +0000980:c:func:`Py_INCREF` to become an independent owner. There are exactly two
981important exceptions to this rule: :c:func:`PyTuple_SetItem` and
982:c:func:`PyList_SetItem`. These functions take over ownership of the item passed
983to them --- even if they fail! (Note that :c:func:`PyDict_SetItem` and friends
Georg Brandl116aa622007-08-15 14:28:22 +0000984don't take over ownership --- they are "normal.")
985
986When a C function is called from Python, it borrows references to its arguments
987from the caller. The caller owns a reference to the object, so the borrowed
988reference's lifetime is guaranteed until the function returns. Only when such a
989borrowed reference must be stored or passed on, it must be turned into an owned
Georg Brandl60203b42010-10-06 10:11:56 +0000990reference by calling :c:func:`Py_INCREF`.
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992The object reference returned from a C function that is called from Python must
993be an owned reference --- ownership is transferred from the function to its
994caller.
995
996
997.. _thinice:
998
999Thin Ice
1000--------
1001
1002There are a few situations where seemingly harmless use of a borrowed reference
1003can lead to problems. These all have to do with implicit invocations of the
1004interpreter, which can cause the owner of a reference to dispose of it.
1005
Georg Brandl60203b42010-10-06 10:11:56 +00001006The first and most important case to know about is using :c:func:`Py_DECREF` on
Georg Brandl116aa622007-08-15 14:28:22 +00001007an unrelated object while borrowing a reference to a list item. For instance::
1008
1009 void
1010 bug(PyObject *list)
1011 {
1012 PyObject *item = PyList_GetItem(list, 0);
1013
Georg Brandl9914dd32007-12-02 23:08:39 +00001014 PyList_SetItem(list, 1, PyLong_FromLong(0L));
Georg Brandl116aa622007-08-15 14:28:22 +00001015 PyObject_Print(item, stdout, 0); /* BUG! */
1016 }
1017
1018This function first borrows a reference to ``list[0]``, then replaces
1019``list[1]`` with the value ``0``, and finally prints the borrowed reference.
1020Looks harmless, right? But it's not!
1021
Georg Brandl60203b42010-10-06 10:11:56 +00001022Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns
Georg Brandl116aa622007-08-15 14:28:22 +00001023references to all its items, so when item 1 is replaced, it has to dispose of
1024the original item 1. Now let's suppose the original item 1 was an instance of a
1025user-defined class, and let's further suppose that the class defined a
1026:meth:`__del__` method. If this class instance has a reference count of 1,
1027disposing of it will call its :meth:`__del__` method.
1028
1029Since it is written in Python, the :meth:`__del__` method can execute arbitrary
1030Python code. Could it perhaps do something to invalidate the reference to
Georg Brandl60203b42010-10-06 10:11:56 +00001031``item`` in :c:func:`bug`? You bet! Assuming that the list passed into
1032:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a
Georg Brandl116aa622007-08-15 14:28:22 +00001033statement to the effect of ``del list[0]``, and assuming this was the last
1034reference to that object, it would free the memory associated with it, thereby
1035invalidating ``item``.
1036
1037The solution, once you know the source of the problem, is easy: temporarily
1038increment the reference count. The correct version of the function reads::
1039
1040 void
1041 no_bug(PyObject *list)
1042 {
1043 PyObject *item = PyList_GetItem(list, 0);
1044
1045 Py_INCREF(item);
Georg Brandl9914dd32007-12-02 23:08:39 +00001046 PyList_SetItem(list, 1, PyLong_FromLong(0L));
Georg Brandl116aa622007-08-15 14:28:22 +00001047 PyObject_Print(item, stdout, 0);
1048 Py_DECREF(item);
1049 }
1050
1051This is a true story. An older version of Python contained variants of this bug
1052and someone spent a considerable amount of time in a C debugger to figure out
1053why his :meth:`__del__` methods would fail...
1054
1055The second case of problems with a borrowed reference is a variant involving
1056threads. Normally, multiple threads in the Python interpreter can't get in each
1057other's way, because there is a global lock protecting Python's entire object
1058space. However, it is possible to temporarily release this lock using the macro
Georg Brandl60203b42010-10-06 10:11:56 +00001059:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using
1060:c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to
Georg Brandl116aa622007-08-15 14:28:22 +00001061let other threads use the processor while waiting for the I/O to complete.
1062Obviously, the following function has the same problem as the previous one::
1063
1064 void
1065 bug(PyObject *list)
1066 {
1067 PyObject *item = PyList_GetItem(list, 0);
1068 Py_BEGIN_ALLOW_THREADS
1069 ...some blocking I/O call...
1070 Py_END_ALLOW_THREADS
1071 PyObject_Print(item, stdout, 0); /* BUG! */
1072 }
1073
1074
1075.. _nullpointers:
1076
1077NULL Pointers
1078-------------
1079
1080In general, functions that take object references as arguments do not expect you
1081to pass them *NULL* pointers, and will dump core (or cause later core dumps) if
1082you do so. Functions that return object references generally return *NULL* only
1083to indicate that an exception occurred. The reason for not testing for *NULL*
1084arguments is that functions often pass the objects they receive on to other
1085function --- if each function were to test for *NULL*, there would be a lot of
1086redundant tests and the code would run more slowly.
1087
1088It is better to test for *NULL* only at the "source:" when a pointer that may be
Georg Brandl60203b42010-10-06 10:11:56 +00001089*NULL* is received, for example, from :c:func:`malloc` or from a function that
Georg Brandl116aa622007-08-15 14:28:22 +00001090may raise an exception.
1091
Georg Brandl60203b42010-10-06 10:11:56 +00001092The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for *NULL*
1093pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF`
Georg Brandl116aa622007-08-15 14:28:22 +00001094do.
1095
1096The macros for checking for a particular object type (``Pytype_Check()``) don't
1097check for *NULL* pointers --- again, there is much code that calls several of
1098these in a row to test an object against various different expected types, and
1099this would generate redundant tests. There are no variants with *NULL*
1100checking.
1101
1102The C function calling mechanism guarantees that the argument list passed to C
1103functions (``args`` in the examples) is never *NULL* --- in fact it guarantees
Emanuele Gaifascdfe9102017-11-24 09:49:57 +01001104that it is always a tuple [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106It is a severe error to ever let a *NULL* pointer "escape" to the Python user.
1107
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001108.. Frank Stajano:
1109 A pedagogically buggy example, along the lines of the previous listing, would
1110 be helpful here -- showing in more concrete terms what sort of actions could
1111 cause the problem. I can't very well imagine it from the description.
Georg Brandl116aa622007-08-15 14:28:22 +00001112
1113
1114.. _cplusplus:
1115
1116Writing Extensions in C++
1117=========================
1118
1119It is possible to write extension modules in C++. Some restrictions apply. If
1120the main program (the Python interpreter) is compiled and linked by the C
1121compiler, global or static objects with constructors cannot be used. This is
1122not a problem if the main program is linked by the C++ compiler. Functions that
1123will be called by the Python interpreter (in particular, module initialization
1124functions) have to be declared using ``extern "C"``. It is unnecessary to
1125enclose the Python header files in ``extern "C" {...}`` --- they use this form
1126already if the symbol ``__cplusplus`` is defined (all recent C++ compilers
1127define this symbol).
1128
1129
Benjamin Petersonb173f782009-05-05 22:31:58 +00001130.. _using-capsules:
Georg Brandl116aa622007-08-15 14:28:22 +00001131
1132Providing a C API for an Extension Module
1133=========================================
1134
1135.. sectionauthor:: Konrad Hinsen <hinsen@cnrs-orleans.fr>
1136
1137
1138Many extension modules just provide new functions and types to be used from
1139Python, but sometimes the code in an extension module can be useful for other
1140extension modules. For example, an extension module could implement a type
1141"collection" which works like lists without order. Just like the standard Python
1142list type has a C API which permits extension modules to create and manipulate
1143lists, this new collection type should have a set of C functions for direct
1144manipulation from other extension modules.
1145
1146At first sight this seems easy: just write the functions (without declaring them
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001147``static``, of course), provide an appropriate header file, and document
Georg Brandl116aa622007-08-15 14:28:22 +00001148the C API. And in fact this would work if all extension modules were always
1149linked statically with the Python interpreter. When modules are used as shared
1150libraries, however, the symbols defined in one module may not be visible to
1151another module. The details of visibility depend on the operating system; some
1152systems use one global namespace for the Python interpreter and all extension
1153modules (Windows, for example), whereas others require an explicit list of
1154imported symbols at module link time (AIX is one example), or offer a choice of
1155different strategies (most Unices). And even if symbols are globally visible,
1156the module whose functions one wishes to call might not have been loaded yet!
1157
1158Portability therefore requires not to make any assumptions about symbol
1159visibility. This means that all symbols in extension modules should be declared
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001160``static``, except for the module's initialization function, in order to
Georg Brandl116aa622007-08-15 14:28:22 +00001161avoid name clashes with other extension modules (as discussed in section
1162:ref:`methodtable`). And it means that symbols that *should* be accessible from
1163other extension modules must be exported in a different way.
1164
1165Python provides a special mechanism to pass C-level information (pointers) from
Benjamin Petersonb173f782009-05-05 22:31:58 +00001166one extension module to another one: Capsules. A Capsule is a Python data type
Georg Brandl60203b42010-10-06 10:11:56 +00001167which stores a pointer (:c:type:`void \*`). Capsules can only be created and
Georg Brandl116aa622007-08-15 14:28:22 +00001168accessed via their C API, but they can be passed around like any other Python
1169object. In particular, they can be assigned to a name in an extension module's
1170namespace. Other extension modules can then import this module, retrieve the
Benjamin Petersonb173f782009-05-05 22:31:58 +00001171value of this name, and then retrieve the pointer from the Capsule.
Georg Brandl116aa622007-08-15 14:28:22 +00001172
Benjamin Petersonb173f782009-05-05 22:31:58 +00001173There are many ways in which Capsules can be used to export the C API of an
1174extension module. Each function could get its own Capsule, or all C API pointers
1175could be stored in an array whose address is published in a Capsule. And the
Georg Brandl116aa622007-08-15 14:28:22 +00001176various tasks of storing and retrieving the pointers can be distributed in
1177different ways between the module providing the code and the client modules.
1178
Benjamin Petersonb173f782009-05-05 22:31:58 +00001179Whichever method you choose, it's important to name your Capsules properly.
Georg Brandl60203b42010-10-06 10:11:56 +00001180The function :c:func:`PyCapsule_New` takes a name parameter
1181(:c:type:`const char \*`); you're permitted to pass in a *NULL* name, but
Benjamin Petersonb173f782009-05-05 22:31:58 +00001182we strongly encourage you to specify a name. Properly named Capsules provide
1183a degree of runtime type-safety; there is no feasible way to tell one unnamed
1184Capsule from another.
1185
1186In particular, Capsules used to expose C APIs should be given a name following
1187this convention::
1188
1189 modulename.attributename
1190
Georg Brandl60203b42010-10-06 10:11:56 +00001191The convenience function :c:func:`PyCapsule_Import` makes it easy to
Benjamin Petersonb173f782009-05-05 22:31:58 +00001192load a C API provided via a Capsule, but only if the Capsule's name
1193matches this convention. This behavior gives C API users a high degree
1194of certainty that the Capsule they load contains the correct C API.
1195
Georg Brandl116aa622007-08-15 14:28:22 +00001196The following example demonstrates an approach that puts most of the burden on
1197the writer of the exporting module, which is appropriate for commonly used
1198library modules. It stores all C API pointers (just one in the example!) in an
Georg Brandl60203b42010-10-06 10:11:56 +00001199array of :c:type:`void` pointers which becomes the value of a Capsule. The header
Georg Brandl116aa622007-08-15 14:28:22 +00001200file corresponding to the module provides a macro that takes care of importing
1201the module and retrieving its C API pointers; client modules only have to call
1202this macro before accessing the C API.
1203
1204The exporting module is a modification of the :mod:`spam` module from section
1205:ref:`extending-simpleexample`. The function :func:`spam.system` does not call
Georg Brandl60203b42010-10-06 10:11:56 +00001206the C library function :c:func:`system` directly, but a function
1207:c:func:`PySpam_System`, which would of course do something more complicated in
Georg Brandl116aa622007-08-15 14:28:22 +00001208reality (such as adding "spam" to every command). This function
Georg Brandl60203b42010-10-06 10:11:56 +00001209:c:func:`PySpam_System` is also exported to other extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
Georg Brandl60203b42010-10-06 10:11:56 +00001211The function :c:func:`PySpam_System` is a plain C function, declared
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001212``static`` like everything else::
Georg Brandl116aa622007-08-15 14:28:22 +00001213
1214 static int
1215 PySpam_System(const char *command)
1216 {
1217 return system(command);
1218 }
1219
Georg Brandl60203b42010-10-06 10:11:56 +00001220The function :c:func:`spam_system` is modified in a trivial way::
Georg Brandl116aa622007-08-15 14:28:22 +00001221
1222 static PyObject *
1223 spam_system(PyObject *self, PyObject *args)
1224 {
1225 const char *command;
1226 int sts;
1227
1228 if (!PyArg_ParseTuple(args, "s", &command))
1229 return NULL;
1230 sts = PySpam_System(command);
Georg Brandlc877a7c2010-11-26 11:55:48 +00001231 return PyLong_FromLong(sts);
Georg Brandl116aa622007-08-15 14:28:22 +00001232 }
1233
1234In the beginning of the module, right after the line ::
1235
Inada Naokic88fece2019-04-13 10:46:21 +09001236 #include <Python.h>
Georg Brandl116aa622007-08-15 14:28:22 +00001237
1238two more lines must be added::
1239
1240 #define SPAM_MODULE
1241 #include "spammodule.h"
1242
1243The ``#define`` is used to tell the header file that it is being included in the
1244exporting module, not a client module. Finally, the module's initialization
1245function must take care of initializing the C API pointer array::
1246
1247 PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001248 PyInit_spam(void)
Georg Brandl116aa622007-08-15 14:28:22 +00001249 {
1250 PyObject *m;
1251 static void *PySpam_API[PySpam_API_pointers];
1252 PyObject *c_api_object;
1253
Martin v. Löwis1a214512008-06-11 05:26:20 +00001254 m = PyModule_Create(&spammodule);
Georg Brandl116aa622007-08-15 14:28:22 +00001255 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001256 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001257
1258 /* Initialize the C API pointer array */
1259 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1260
Benjamin Petersonb173f782009-05-05 22:31:58 +00001261 /* Create a Capsule containing the API pointer array's address */
1262 c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);
Georg Brandl116aa622007-08-15 14:28:22 +00001263
1264 if (c_api_object != NULL)
1265 PyModule_AddObject(m, "_C_API", c_api_object);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001266 return m;
Georg Brandl116aa622007-08-15 14:28:22 +00001267 }
1268
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001269Note that ``PySpam_API`` is declared ``static``; otherwise the pointer
Martin v. Löwis1a214512008-06-11 05:26:20 +00001270array would disappear when :func:`PyInit_spam` terminates!
Georg Brandl116aa622007-08-15 14:28:22 +00001271
1272The bulk of the work is in the header file :file:`spammodule.h`, which looks
1273like this::
1274
1275 #ifndef Py_SPAMMODULE_H
1276 #define Py_SPAMMODULE_H
1277 #ifdef __cplusplus
1278 extern "C" {
1279 #endif
1280
1281 /* Header file for spammodule */
1282
1283 /* C API functions */
1284 #define PySpam_System_NUM 0
1285 #define PySpam_System_RETURN int
1286 #define PySpam_System_PROTO (const char *command)
1287
1288 /* Total number of C API pointers */
1289 #define PySpam_API_pointers 1
1290
1291
1292 #ifdef SPAM_MODULE
1293 /* This section is used when compiling spammodule.c */
1294
1295 static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1296
1297 #else
1298 /* This section is used in modules that use spammodule's API */
1299
1300 static void **PySpam_API;
1301
1302 #define PySpam_System \
1303 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1304
Benjamin Petersonb173f782009-05-05 22:31:58 +00001305 /* Return -1 on error, 0 on success.
1306 * PyCapsule_Import will set an exception if there's an error.
1307 */
Georg Brandl116aa622007-08-15 14:28:22 +00001308 static int
1309 import_spam(void)
1310 {
Benjamin Petersonb173f782009-05-05 22:31:58 +00001311 PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
1312 return (PySpam_API != NULL) ? 0 : -1;
Georg Brandl116aa622007-08-15 14:28:22 +00001313 }
1314
1315 #endif
1316
1317 #ifdef __cplusplus
1318 }
1319 #endif
1320
1321 #endif /* !defined(Py_SPAMMODULE_H) */
1322
1323All that a client module must do in order to have access to the function
Georg Brandl60203b42010-10-06 10:11:56 +00001324:c:func:`PySpam_System` is to call the function (or rather macro)
1325:c:func:`import_spam` in its initialization function::
Georg Brandl116aa622007-08-15 14:28:22 +00001326
1327 PyMODINIT_FUNC
Benjamin Peterson7c435242009-03-24 01:40:39 +00001328 PyInit_client(void)
Georg Brandl116aa622007-08-15 14:28:22 +00001329 {
1330 PyObject *m;
1331
Georg Brandl21151762009-03-31 15:52:41 +00001332 m = PyModule_Create(&clientmodule);
Georg Brandl116aa622007-08-15 14:28:22 +00001333 if (m == NULL)
Georg Brandl21151762009-03-31 15:52:41 +00001334 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001335 if (import_spam() < 0)
Georg Brandl21151762009-03-31 15:52:41 +00001336 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001337 /* additional initialization can happen here */
Georg Brandl21151762009-03-31 15:52:41 +00001338 return m;
Georg Brandl116aa622007-08-15 14:28:22 +00001339 }
1340
1341The main disadvantage of this approach is that the file :file:`spammodule.h` is
1342rather complicated. However, the basic structure is the same for each function
1343that is exported, so it has to be learned only once.
1344
Benjamin Petersonb173f782009-05-05 22:31:58 +00001345Finally it should be mentioned that Capsules offer additional functionality,
Georg Brandl116aa622007-08-15 14:28:22 +00001346which is especially useful for memory allocation and deallocation of the pointer
Benjamin Petersonb173f782009-05-05 22:31:58 +00001347stored in a Capsule. The details are described in the Python/C API Reference
1348Manual in the section :ref:`capsules` and in the implementation of Capsules (files
1349:file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` in the Python source
Georg Brandl116aa622007-08-15 14:28:22 +00001350code distribution).
1351
1352.. rubric:: Footnotes
1353
1354.. [#] An interface for this function already exists in the standard module :mod:`os`
1355 --- it was chosen as a simple and straightforward example.
1356
1357.. [#] The metaphor of "borrowing" a reference is not completely correct: the owner
1358 still has a copy of the reference.
1359
1360.. [#] Checking that the reference count is at least 1 **does not work** --- the
1361 reference count itself could be in freed memory and may thus be reused for
1362 another object!
1363
1364.. [#] These guarantees don't hold when you use the "old" style calling convention ---
1365 this is still found in much existing code.