blob: 5b32a2cdc5506efa302d979a76c2e8dda136040c [file] [log] [blame]
Stéphane Wirtelcbb64842019-05-17 11:55:34 +02001.. highlight:: c
Georg Brandl116aa622007-08-15 14:28:22 +00002
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
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200120return ``NULL`` immediately (as we saw in the example).
Georg Brandl116aa622007-08-15 14:28:22 +0000121
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
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200130(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
Georg Brandl116aa622007-08-15 14:28:22 +0000132second 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
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200155: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
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200161fails, *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`)
Brandt Bucher224b8aa2019-09-12 05:11:20 -0700212with an exception object::
Georg Brandl116aa622007-08-15 14:28:22 +0000213
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);
Brandt Bucher224b8aa2019-09-12 05:11:20 -0700224 Py_XINCREF(SpamError);
225 if (PyModule_AddObject(m, "error", SpamError) < 0) {
226 Py_XDECREF(SpamError);
227 Py_CLEAR(SpamError);
228 Py_DECREF(m);
229 return NULL;
230 }
231
Martin v. Löwis1a214512008-06-11 05:26:20 +0000232 return m;
Georg Brandl116aa622007-08-15 14:28:22 +0000233 }
234
235Note that the Python name for the exception object is :exc:`spam.error`. The
Georg Brandl60203b42010-10-06 10:11:56 +0000236:c:func:`PyErr_NewException` function may create a class with the base class
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200237being :exc:`Exception` (unless another class is passed in instead of ``NULL``),
Georg Brandl116aa622007-08-15 14:28:22 +0000238described in :ref:`bltin-exceptions`.
239
Georg Brandl60203b42010-10-06 10:11:56 +0000240Note also that the :c:data:`SpamError` variable retains a reference to the newly
Georg Brandl116aa622007-08-15 14:28:22 +0000241created exception class; this is intentional! Since the exception could be
242removed from the module by external code, an owned reference to the class is
Georg Brandl60203b42010-10-06 10:11:56 +0000243needed to ensure that it will not be discarded, causing :c:data:`SpamError` to
Georg Brandl116aa622007-08-15 14:28:22 +0000244become a dangling pointer. Should it become a dangling pointer, C code which
245raises the exception could cause a core dump or other unintended side effects.
246
Georg Brandl9c491c92010-08-02 20:21:21 +0000247We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this
Georg Brandl116aa622007-08-15 14:28:22 +0000248sample.
249
Georg Brandl9c491c92010-08-02 20:21:21 +0000250The :exc:`spam.error` exception can be raised in your extension module using a
Georg Brandl60203b42010-10-06 10:11:56 +0000251call to :c:func:`PyErr_SetString` as shown below::
Georg Brandl9c491c92010-08-02 20:21:21 +0000252
253 static PyObject *
254 spam_system(PyObject *self, PyObject *args)
255 {
256 const char *command;
257 int sts;
258
259 if (!PyArg_ParseTuple(args, "s", &command))
260 return NULL;
261 sts = system(command);
262 if (sts < 0) {
263 PyErr_SetString(SpamError, "System command failed");
264 return NULL;
265 }
266 return PyLong_FromLong(sts);
267 }
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270.. _backtoexample:
271
272Back to the Example
273===================
274
275Going back to our example function, you should now be able to understand this
276statement::
277
278 if (!PyArg_ParseTuple(args, "s", &command))
279 return NULL;
280
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200281It returns ``NULL`` (the error indicator for functions returning object pointers)
Georg Brandl116aa622007-08-15 14:28:22 +0000282if an error is detected in the argument list, relying on the exception set by
Georg Brandl60203b42010-10-06 10:11:56 +0000283:c:func:`PyArg_ParseTuple`. Otherwise the string value of the argument has been
284copied to the local variable :c:data:`command`. This is a pointer assignment and
Georg Brandl116aa622007-08-15 14:28:22 +0000285you are not supposed to modify the string to which it points (so in Standard C,
Georg Brandl60203b42010-10-06 10:11:56 +0000286the variable :c:data:`command` should properly be declared as ``const char
Georg Brandl116aa622007-08-15 14:28:22 +0000287*command``).
288
Georg Brandl60203b42010-10-06 10:11:56 +0000289The next statement is a call to the Unix function :c:func:`system`, passing it
290the string we just got from :c:func:`PyArg_ParseTuple`::
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292 sts = system(command);
293
Georg Brandl60203b42010-10-06 10:11:56 +0000294Our :func:`spam.system` function must return the value of :c:data:`sts` as a
Georg Brandlc877a7c2010-11-26 11:55:48 +0000295Python object. This is done using the function :c:func:`PyLong_FromLong`. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Georg Brandlc877a7c2010-11-26 11:55:48 +0000297 return PyLong_FromLong(sts);
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299In this case, it will return an integer object. (Yes, even integers are objects
300on the heap in Python!)
301
302If you have a C function that returns no useful argument (a function returning
Georg Brandl60203b42010-10-06 10:11:56 +0000303:c:type:`void`), the corresponding Python function must return ``None``. You
304need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE`
Georg Brandl116aa622007-08-15 14:28:22 +0000305macro)::
306
307 Py_INCREF(Py_None);
308 return Py_None;
309
Georg Brandl60203b42010-10-06 10:11:56 +0000310:c:data:`Py_None` is the C name for the special Python object ``None``. It is a
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200311genuine Python object rather than a ``NULL`` pointer, which means "error" in most
Georg Brandl116aa622007-08-15 14:28:22 +0000312contexts, as we have seen.
313
314
315.. _methodtable:
316
317The Module's Method Table and Initialization Function
318=====================================================
319
Georg Brandl60203b42010-10-06 10:11:56 +0000320I promised to show how :c:func:`spam_system` is called from Python programs.
Georg Brandl116aa622007-08-15 14:28:22 +0000321First, we need to list its name and address in a "method table"::
322
323 static PyMethodDef SpamMethods[] = {
324 ...
325 {"system", spam_system, METH_VARARGS,
326 "Execute a shell command."},
327 ...
328 {NULL, NULL, 0, NULL} /* Sentinel */
329 };
330
331Note the third entry (``METH_VARARGS``). This is a flag telling the interpreter
332the calling convention to be used for the C function. It should normally always
333be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means
Georg Brandl60203b42010-10-06 10:11:56 +0000334that an obsolete variant of :c:func:`PyArg_ParseTuple` is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336When using only ``METH_VARARGS``, the function should expect the Python-level
337parameters to be passed in as a tuple acceptable for parsing via
Georg Brandl60203b42010-10-06 10:11:56 +0000338:c:func:`PyArg_ParseTuple`; more information on this function is provided below.
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340The :const:`METH_KEYWORDS` bit may be set in the third field if keyword
341arguments should be passed to the function. In this case, the C function should
Eli Bendersky44fb6132012-02-11 10:27:31 +0200342accept a third ``PyObject *`` parameter which will be a dictionary of keywords.
Georg Brandl60203b42010-10-06 10:11:56 +0000343Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a
Georg Brandl116aa622007-08-15 14:28:22 +0000344function.
345
Martin v. Löwis1a214512008-06-11 05:26:20 +0000346The method table must be referenced in the module definition structure::
347
Benjamin Peterson3851d122008-10-20 21:04:06 +0000348 static struct PyModuleDef spammodule = {
Sergey Fedoseevd9a2b992017-08-30 19:50:40 +0500349 PyModuleDef_HEAD_INIT,
350 "spam", /* name of module */
351 spam_doc, /* module documentation, may be NULL */
352 -1, /* size of per-interpreter state of the module,
353 or -1 if the module keeps state in global variables. */
354 SpamMethods
Martin v. Löwis1a214512008-06-11 05:26:20 +0000355 };
356
357This structure, in turn, must be passed to the interpreter in the module's
Georg Brandl116aa622007-08-15 14:28:22 +0000358initialization function. The initialization function must be named
Georg Brandl60203b42010-10-06 10:11:56 +0000359:c:func:`PyInit_name`, where *name* is the name of the module, and should be the
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000360only non-\ ``static`` item defined in the module file::
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362 PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +0000363 PyInit_spam(void)
Georg Brandl116aa622007-08-15 14:28:22 +0000364 {
Martin v. Löwis1a214512008-06-11 05:26:20 +0000365 return PyModule_Create(&spammodule);
Georg Brandl116aa622007-08-15 14:28:22 +0000366 }
367
Benjamin Peterson71e30a02008-12-24 16:27:25 +0000368Note that PyMODINIT_FUNC declares the function as ``PyObject *`` return type,
369declares any special linkage declarations required by the platform, and for C++
Georg Brandl116aa622007-08-15 14:28:22 +0000370declares the function as ``extern "C"``.
371
372When the Python program imports module :mod:`spam` for the first time,
Georg Brandl60203b42010-10-06 10:11:56 +0000373:c:func:`PyInit_spam` is called. (See below for comments about embedding Python.)
374It calls :c:func:`PyModule_Create`, which returns a module object, and
Georg Brandl116aa622007-08-15 14:28:22 +0000375inserts built-in function objects into the newly created module based upon the
Georg Brandl60203b42010-10-06 10:11:56 +0000376table (an array of :c:type:`PyMethodDef` structures) found in the module definition.
377:c:func:`PyModule_Create` returns a pointer to the module object
Martin v. Löwis1a214512008-06-11 05:26:20 +0000378that it creates. It may abort with a fatal error for
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200379certain errors, or return ``NULL`` if the module could not be initialized
Martin v. Löwis1a214512008-06-11 05:26:20 +0000380satisfactorily. The init function must return the module object to its caller,
381so that it then gets inserted into ``sys.modules``.
Georg Brandl116aa622007-08-15 14:28:22 +0000382
Georg Brandl60203b42010-10-06 10:11:56 +0000383When embedding Python, the :c:func:`PyInit_spam` function is not called
384automatically unless there's an entry in the :c:data:`PyImport_Inittab` table.
385To add the module to the initialization table, use :c:func:`PyImport_AppendInittab`,
Martin v. Löwis1a214512008-06-11 05:26:20 +0000386optionally followed by an import of the module::
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388 int
389 main(int argc, char *argv[])
390 {
Victor Stinner25e014b2014-08-01 12:28:49 +0200391 wchar_t *program = Py_DecodeLocale(argv[0], NULL);
392 if (program == NULL) {
393 fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
394 exit(1);
395 }
396
Georg Brandlc4a55fc2010-02-06 18:46:57 +0000397 /* Add a built-in module, before Py_Initialize */
Martin v. Löwis1a214512008-06-11 05:26:20 +0000398 PyImport_AppendInittab("spam", PyInit_spam);
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400 /* Pass argv[0] to the Python interpreter */
Victor Stinner25e014b2014-08-01 12:28:49 +0200401 Py_SetProgramName(program);
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403 /* Initialize the Python interpreter. Required. */
404 Py_Initialize();
405
Martin v. Löwis1a214512008-06-11 05:26:20 +0000406 /* Optionally import the module; alternatively,
407 import can be deferred until the embedded script
408 imports it. */
409 PyImport_ImportModule("spam");
Georg Brandl116aa622007-08-15 14:28:22 +0000410
Georg Brandl49c6fc92013-10-06 13:14:10 +0200411 ...
412
Victor Stinner25e014b2014-08-01 12:28:49 +0200413 PyMem_RawFree(program);
414 return 0;
415 }
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417.. note::
418
419 Removing entries from ``sys.modules`` or importing compiled modules into
Georg Brandl60203b42010-10-06 10:11:56 +0000420 multiple interpreters within a process (or following a :c:func:`fork` without an
421 intervening :c:func:`exec`) can create problems for some extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +0000422 Extension module authors should exercise caution when initializing internal data
423 structures.
424
425A more substantial example module is included in the Python source distribution
426as :file:`Modules/xxmodule.c`. This file may be used as a template or simply
Benjamin Peterson2614cda2010-03-21 22:36:19 +0000427read as an example.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Nick Coghlan2ab5b092015-07-03 19:49:15 +1000429.. note::
430
431 Unlike our ``spam`` example, ``xxmodule`` uses *multi-phase initialization*
432 (new in Python 3.5), where a PyModuleDef structure is returned from
433 ``PyInit_spam``, and creation of the module is left to the import machinery.
434 For details on multi-phase initialization, see :PEP:`489`.
435
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437.. _compilation:
438
439Compilation and Linkage
440=======================
441
442There are two more things to do before you can use your new extension: compiling
443and linking it with the Python system. If you use dynamic loading, the details
444may depend on the style of dynamic loading your system uses; see the chapters
445about building extension modules (chapter :ref:`building`) and additional
446information that pertains only to building on Windows (chapter
447:ref:`building-on-windows`) for more information about this.
448
449If you can't use dynamic loading, or if you want to make your module a permanent
450part of the Python interpreter, you will have to change the configuration setup
451and rebuild the interpreter. Luckily, this is very simple on Unix: just place
452your file (:file:`spammodule.c` for example) in the :file:`Modules/` directory
453of an unpacked source distribution, add a line to the file
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300454:file:`Modules/Setup.local` describing your file:
455
456.. code-block:: sh
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458 spam spammodule.o
459
460and rebuild the interpreter by running :program:`make` in the toplevel
461directory. You can also run :program:`make` in the :file:`Modules/`
462subdirectory, but then you must first rebuild :file:`Makefile` there by running
463':program:`make` Makefile'. (This is necessary each time you change the
464:file:`Setup` file.)
465
466If your module requires additional libraries to link with, these can be listed
Serhiy Storchaka46936d52018-04-08 19:18:04 +0300467on the line in the configuration file as well, for instance:
468
469.. code-block:: sh
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471 spam spammodule.o -lX11
472
473
474.. _callingpython:
475
476Calling Python Functions from C
477===============================
478
479So far we have concentrated on making C functions callable from Python. The
480reverse is also useful: calling Python functions from C. This is especially the
481case for libraries that support so-called "callback" functions. If a C
482interface makes use of callbacks, the equivalent Python often needs to provide a
483callback mechanism to the Python programmer; the implementation will require
484calling the Python callback functions from a C callback. Other uses are also
485imaginable.
486
487Fortunately, the Python interpreter is easily called recursively, and there is a
488standard interface to call a Python function. (I won't dwell on how to call the
489Python parser with a particular string as input --- if you're interested, have a
490look at the implementation of the :option:`-c` command line option in
Georg Brandl22291c52007-09-06 14:49:02 +0000491:file:`Modules/main.c` from the Python source code.)
Georg Brandl116aa622007-08-15 14:28:22 +0000492
493Calling a Python function is easy. First, the Python program must somehow pass
494you the Python function object. You should provide a function (or some other
495interface) to do this. When this function is called, save a pointer to the
Georg Brandl60203b42010-10-06 10:11:56 +0000496Python function object (be careful to :c:func:`Py_INCREF` it!) in a global
Georg Brandl116aa622007-08-15 14:28:22 +0000497variable --- or wherever you see fit. For example, the following function might
498be part of a module definition::
499
500 static PyObject *my_callback = NULL;
501
502 static PyObject *
503 my_set_callback(PyObject *dummy, PyObject *args)
504 {
505 PyObject *result = NULL;
506 PyObject *temp;
507
508 if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
509 if (!PyCallable_Check(temp)) {
510 PyErr_SetString(PyExc_TypeError, "parameter must be callable");
511 return NULL;
512 }
513 Py_XINCREF(temp); /* Add a reference to new callback */
514 Py_XDECREF(my_callback); /* Dispose of previous callback */
515 my_callback = temp; /* Remember new callback */
516 /* Boilerplate to return "None" */
517 Py_INCREF(Py_None);
518 result = Py_None;
519 }
520 return result;
521 }
522
523This function must be registered with the interpreter using the
524:const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`. The
Georg Brandl60203b42010-10-06 10:11:56 +0000525:c:func:`PyArg_ParseTuple` function and its arguments are documented in section
Georg Brandl116aa622007-08-15 14:28:22 +0000526:ref:`parsetuple`.
527
Georg Brandl60203b42010-10-06 10:11:56 +0000528The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200529reference count of an object and are safe in the presence of ``NULL`` pointers
530(but note that *temp* will not be ``NULL`` in this context). More info on them
Georg Brandl116aa622007-08-15 14:28:22 +0000531in section :ref:`refcounts`.
532
Benjamin Petersond23f8222009-04-05 19:13:16 +0000533.. index:: single: PyObject_CallObject()
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535Later, when it is time to call the function, you call the C function
Georg Brandl60203b42010-10-06 10:11:56 +0000536:c:func:`PyObject_CallObject`. This function has two arguments, both pointers to
Georg Brandl116aa622007-08-15 14:28:22 +0000537arbitrary Python objects: the Python function, and the argument list. The
538argument list must always be a tuple object, whose length is the number of
Serhiy Storchakae835b312019-10-30 21:37:16 +0200539arguments. To call the Python function with no arguments, pass in ``NULL``, or
Christian Heimesd8654cf2007-12-02 15:22:16 +0000540an empty tuple; to call it with one argument, pass a singleton tuple.
Georg Brandl60203b42010-10-06 10:11:56 +0000541:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero
Christian Heimesd8654cf2007-12-02 15:22:16 +0000542or more format codes between parentheses. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544 int arg;
545 PyObject *arglist;
546 PyObject *result;
547 ...
548 arg = 123;
549 ...
550 /* Time to call the callback */
551 arglist = Py_BuildValue("(i)", arg);
Benjamin Petersond23f8222009-04-05 19:13:16 +0000552 result = PyObject_CallObject(my_callback, arglist);
Georg Brandl116aa622007-08-15 14:28:22 +0000553 Py_DECREF(arglist);
554
Georg Brandl60203b42010-10-06 10:11:56 +0000555:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return
556value of the Python function. :c:func:`PyObject_CallObject` is
Georg Brandl116aa622007-08-15 14:28:22 +0000557"reference-count-neutral" with respect to its arguments. In the example a new
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +0200558tuple was created to serve as the argument list, which is
559:c:func:`Py_DECREF`\ -ed immediately after the :c:func:`PyObject_CallObject`
560call.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
Georg Brandl60203b42010-10-06 10:11:56 +0000562The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand
Georg Brandl116aa622007-08-15 14:28:22 +0000563new object, or it is an existing object whose reference count has been
564incremented. So, unless you want to save it in a global variable, you should
Georg Brandl60203b42010-10-06 10:11:56 +0000565somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not
Georg Brandl116aa622007-08-15 14:28:22 +0000566interested in its value.
567
568Before you do this, however, it is important to check that the return value
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200569isn't ``NULL``. If it is, the Python function terminated by raising an exception.
Georg Brandl60203b42010-10-06 10:11:56 +0000570If the C code that called :c:func:`PyObject_CallObject` is called from Python, it
Georg Brandl116aa622007-08-15 14:28:22 +0000571should now return an error indication to its Python caller, so the interpreter
572can print a stack trace, or the calling Python code can handle the exception.
573If this is not possible or desirable, the exception should be cleared by calling
Georg Brandl60203b42010-10-06 10:11:56 +0000574:c:func:`PyErr_Clear`. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000575
576 if (result == NULL)
577 return NULL; /* Pass error back */
578 ...use result...
Georg Brandl48310cd2009-01-03 21:18:54 +0000579 Py_DECREF(result);
Georg Brandl116aa622007-08-15 14:28:22 +0000580
581Depending on the desired interface to the Python callback function, you may also
Georg Brandl60203b42010-10-06 10:11:56 +0000582have to provide an argument list to :c:func:`PyObject_CallObject`. In some cases
Georg Brandl116aa622007-08-15 14:28:22 +0000583the argument list is also provided by the Python program, through the same
584interface that specified the callback function. It can then be saved and used
585in the same manner as the function object. In other cases, you may have to
586construct a new tuple to pass as the argument list. The simplest way to do this
Georg Brandl60203b42010-10-06 10:11:56 +0000587is to call :c:func:`Py_BuildValue`. For example, if you want to pass an integral
Georg Brandl116aa622007-08-15 14:28:22 +0000588event code, you might use the following code::
589
590 PyObject *arglist;
591 ...
592 arglist = Py_BuildValue("(l)", eventcode);
Benjamin Petersond23f8222009-04-05 19:13:16 +0000593 result = PyObject_CallObject(my_callback, arglist);
Georg Brandl116aa622007-08-15 14:28:22 +0000594 Py_DECREF(arglist);
595 if (result == NULL)
596 return NULL; /* Pass error back */
597 /* Here maybe use the result */
598 Py_DECREF(result);
599
600Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before
Christian Heimesd8654cf2007-12-02 15:22:16 +0000601the error check! Also note that strictly speaking this code is not complete:
Georg Brandl60203b42010-10-06 10:11:56 +0000602:c:func:`Py_BuildValue` may run out of memory, and this should be checked.
Georg Brandl116aa622007-08-15 14:28:22 +0000603
Georg Brandl48310cd2009-01-03 21:18:54 +0000604You may also call a function with keyword arguments by using
Georg Brandl60203b42010-10-06 10:11:56 +0000605:c:func:`PyObject_Call`, which supports arguments and keyword arguments. As in
606the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::
Christian Heimesd8654cf2007-12-02 15:22:16 +0000607
608 PyObject *dict;
609 ...
610 dict = Py_BuildValue("{s:i}", "name", val);
Benjamin Petersond23f8222009-04-05 19:13:16 +0000611 result = PyObject_Call(my_callback, NULL, dict);
Christian Heimesd8654cf2007-12-02 15:22:16 +0000612 Py_DECREF(dict);
613 if (result == NULL)
614 return NULL; /* Pass error back */
615 /* Here maybe use the result */
616 Py_DECREF(result);
Georg Brandl116aa622007-08-15 14:28:22 +0000617
Benjamin Petersond23f8222009-04-05 19:13:16 +0000618
Georg Brandl116aa622007-08-15 14:28:22 +0000619.. _parsetuple:
620
621Extracting Parameters in Extension Functions
622============================================
623
624.. index:: single: PyArg_ParseTuple()
625
Georg Brandl60203b42010-10-06 10:11:56 +0000626The :c:func:`PyArg_ParseTuple` function is declared as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300628 int PyArg_ParseTuple(PyObject *arg, const char *format, ...);
Georg Brandl116aa622007-08-15 14:28:22 +0000629
630The *arg* argument must be a tuple object containing an argument list passed
631from Python to a C function. The *format* argument must be a format string,
632whose syntax is explained in :ref:`arg-parsing` in the Python/C API Reference
633Manual. The remaining arguments must be addresses of variables whose type is
634determined by the format string.
635
Georg Brandl60203b42010-10-06 10:11:56 +0000636Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have
Georg Brandl116aa622007-08-15 14:28:22 +0000637the required types, it cannot check the validity of the addresses of C variables
638passed to the call: if you make mistakes there, your code will probably crash or
639at least overwrite random bits in memory. So be careful!
640
641Note that any Python object references which are provided to the caller are
642*borrowed* references; do not decrement their reference count!
643
644Some example calls::
645
Gregory P. Smith02c3b5c2008-11-23 23:49:16 +0000646 #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */
647 #include <Python.h>
648
649::
650
Georg Brandl116aa622007-08-15 14:28:22 +0000651 int ok;
652 int i, j;
653 long k, l;
654 const char *s;
Gregory P. Smith02c3b5c2008-11-23 23:49:16 +0000655 Py_ssize_t size;
Georg Brandl116aa622007-08-15 14:28:22 +0000656
657 ok = PyArg_ParseTuple(args, ""); /* No arguments */
658 /* Python call: f() */
659
660::
661
662 ok = PyArg_ParseTuple(args, "s", &s); /* A string */
663 /* Possible Python call: f('whoops!') */
664
665::
666
667 ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
668 /* Possible Python call: f(1, 2, 'three') */
669
670::
671
672 ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
673 /* A pair of ints and a string, whose size is also returned */
674 /* Possible Python call: f((1, 2), 'three') */
675
676::
677
678 {
679 const char *file;
680 const char *mode = "r";
681 int bufsize = 0;
682 ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
683 /* A string, and optionally another string and an integer */
684 /* Possible Python calls:
685 f('spam')
686 f('spam', 'w')
687 f('spam', 'wb', 100000) */
688 }
689
690::
691
692 {
693 int left, top, right, bottom, h, v;
694 ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
695 &left, &top, &right, &bottom, &h, &v);
696 /* A rectangle and a point */
697 /* Possible Python call:
698 f(((0, 0), (400, 300)), (10, 10)) */
699 }
700
701::
702
703 {
704 Py_complex c;
705 ok = PyArg_ParseTuple(args, "D:myfunction", &c);
706 /* a complex, also providing a function name for errors */
707 /* Possible Python call: myfunction(1+2j) */
708 }
709
710
711.. _parsetupleandkeywords:
712
713Keyword Parameters for Extension Functions
714==========================================
715
716.. index:: single: PyArg_ParseTupleAndKeywords()
717
Georg Brandl60203b42010-10-06 10:11:56 +0000718The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000719
720 int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300721 const char *format, char *kwlist[], ...);
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723The *arg* and *format* parameters are identical to those of the
Georg Brandl60203b42010-10-06 10:11:56 +0000724:c:func:`PyArg_ParseTuple` function. The *kwdict* parameter is the dictionary of
Georg Brandl116aa622007-08-15 14:28:22 +0000725keywords received as the third parameter from the Python runtime. The *kwlist*
Serhiy Storchaka25fc0882019-10-30 12:03:20 +0200726parameter is a ``NULL``-terminated list of strings which identify the parameters;
Georg Brandl116aa622007-08-15 14:28:22 +0000727the names are matched with the type information from *format* from left to
Georg Brandl60203b42010-10-06 10:11:56 +0000728right. On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise
Georg Brandl116aa622007-08-15 14:28:22 +0000729it returns false and raises an appropriate exception.
730
731.. note::
732
733 Nested tuples cannot be parsed when using keyword arguments! Keyword parameters
734 passed in which are not present in the *kwlist* will cause :exc:`TypeError` to
735 be raised.
736
737.. index:: single: Philbrick, Geoff
738
739Here is an example module which uses keywords, based on an example by Geoff
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000740Philbrick (philbrick@hks.com)::
Georg Brandl116aa622007-08-15 14:28:22 +0000741
Inada Naokic88fece2019-04-13 10:46:21 +0900742 #define PY_SSIZE_T_CLEAN /* Make "s#" use Py_ssize_t rather than int. */
743 #include <Python.h>
Georg Brandl116aa622007-08-15 14:28:22 +0000744
745 static PyObject *
746 keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
Georg Brandl48310cd2009-01-03 21:18:54 +0000747 {
Georg Brandl116aa622007-08-15 14:28:22 +0000748 int voltage;
Serhiy Storchaka84b8e922017-03-30 10:01:03 +0300749 const char *state = "a stiff";
750 const char *action = "voom";
751 const char *type = "Norwegian Blue";
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753 static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
754
Georg Brandl48310cd2009-01-03 21:18:54 +0000755 if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
Georg Brandl116aa622007-08-15 14:28:22 +0000756 &voltage, &state, &action, &type))
Georg Brandl48310cd2009-01-03 21:18:54 +0000757 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Georg Brandl48310cd2009-01-03 21:18:54 +0000759 printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
Georg Brandl116aa622007-08-15 14:28:22 +0000760 action, voltage);
761 printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
762
Georg Brandla072de12013-10-06 20:46:08 +0200763 Py_RETURN_NONE;
Georg Brandl116aa622007-08-15 14:28:22 +0000764 }
765
766 static PyMethodDef keywdarg_methods[] = {
767 /* The cast of the function is necessary since PyCFunction values
768 * only take two PyObject* parameters, and keywdarg_parrot() takes
769 * three.
770 */
Serhiy Storchaka62be7422018-11-27 13:27:31 +0200771 {"parrot", (PyCFunction)(void(*)(void))keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
Georg Brandl116aa622007-08-15 14:28:22 +0000772 "Print a lovely skit to standard output."},
773 {NULL, NULL, 0, NULL} /* sentinel */
774 };
775
Eli Bendersky8f773492012-08-15 14:49:49 +0300776 static struct PyModuleDef keywdargmodule = {
777 PyModuleDef_HEAD_INIT,
778 "keywdarg",
779 NULL,
780 -1,
781 keywdarg_methods
782 };
Georg Brandl116aa622007-08-15 14:28:22 +0000783
Eli Bendersky8f773492012-08-15 14:49:49 +0300784 PyMODINIT_FUNC
785 PyInit_keywdarg(void)
Georg Brandl116aa622007-08-15 14:28:22 +0000786 {
Eli Bendersky8f773492012-08-15 14:49:49 +0300787 return PyModule_Create(&keywdargmodule);
Georg Brandl116aa622007-08-15 14:28:22 +0000788 }
789
790
791.. _buildvalue:
792
793Building Arbitrary Values
794=========================
795
Georg Brandl60203b42010-10-06 10:11:56 +0000796This function is the counterpart to :c:func:`PyArg_ParseTuple`. It is declared
Georg Brandl116aa622007-08-15 14:28:22 +0000797as follows::
798
Serhiy Storchaka03863d22015-06-21 17:11:21 +0300799 PyObject *Py_BuildValue(const char *format, ...);
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801It recognizes a set of format units similar to the ones recognized by
Georg Brandl60203b42010-10-06 10:11:56 +0000802:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function,
Georg Brandl116aa622007-08-15 14:28:22 +0000803not output) must not be pointers, just values. It returns a new Python object,
804suitable for returning from a C function called from Python.
805
Georg Brandl60203b42010-10-06 10:11:56 +0000806One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its
Georg Brandl116aa622007-08-15 14:28:22 +0000807first argument to be a tuple (since Python argument lists are always represented
Georg Brandl60203b42010-10-06 10:11:56 +0000808as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple. It
Georg Brandl116aa622007-08-15 14:28:22 +0000809builds a tuple only if its format string contains two or more format units. If
810the format string is empty, it returns ``None``; if it contains exactly one
811format unit, it returns whatever object is described by that format unit. To
812force it to return a tuple of size 0 or one, parenthesize the format string.
813
Martin Panter1050d2d2016-07-26 11:18:21 +0200814Examples (to the left the call, to the right the resulting Python value):
815
816.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000817
818 Py_BuildValue("") None
819 Py_BuildValue("i", 123) 123
820 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
821 Py_BuildValue("s", "hello") 'hello'
822 Py_BuildValue("y", "hello") b'hello'
823 Py_BuildValue("ss", "hello", "world") ('hello', 'world')
824 Py_BuildValue("s#", "hello", 4) 'hell'
825 Py_BuildValue("y#", "hello", 4) b'hell'
826 Py_BuildValue("()") ()
827 Py_BuildValue("(i)", 123) (123,)
828 Py_BuildValue("(ii)", 123, 456) (123, 456)
829 Py_BuildValue("(i,i)", 123, 456) (123, 456)
830 Py_BuildValue("[i,i]", 123, 456) [123, 456]
831 Py_BuildValue("{s:i,s:i}",
832 "abc", 123, "def", 456) {'abc': 123, 'def': 456}
833 Py_BuildValue("((ii)(ii)) (ii)",
834 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))
835
836
837.. _refcounts:
838
839Reference Counts
840================
841
842In languages like C or C++, the programmer is responsible for dynamic allocation
843and deallocation of memory on the heap. In C, this is done using the functions
Georg Brandl60203b42010-10-06 10:11:56 +0000844:c:func:`malloc` and :c:func:`free`. In C++, the operators ``new`` and
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000845``delete`` are used with essentially the same meaning and we'll restrict
Georg Brandl116aa622007-08-15 14:28:22 +0000846the following discussion to the C case.
847
Georg Brandl60203b42010-10-06 10:11:56 +0000848Every block of memory allocated with :c:func:`malloc` should eventually be
849returned to the pool of available memory by exactly one call to :c:func:`free`.
850It is important to call :c:func:`free` at the right time. If a block's address
851is forgotten but :c:func:`free` is not called for it, the memory it occupies
Georg Brandl116aa622007-08-15 14:28:22 +0000852cannot be reused until the program terminates. This is called a :dfn:`memory
Georg Brandl60203b42010-10-06 10:11:56 +0000853leak`. On the other hand, if a program calls :c:func:`free` for a block and then
Georg Brandl116aa622007-08-15 14:28:22 +0000854continues to use the block, it creates a conflict with re-use of the block
Georg Brandl60203b42010-10-06 10:11:56 +0000855through another :c:func:`malloc` call. This is called :dfn:`using freed memory`.
Georg Brandl116aa622007-08-15 14:28:22 +0000856It has the same bad consequences as referencing uninitialized data --- core
857dumps, wrong results, mysterious crashes.
858
859Common causes of memory leaks are unusual paths through the code. For instance,
860a function may allocate a block of memory, do some calculation, and then free
861the block again. Now a change in the requirements for the function may add a
862test to the calculation that detects an error condition and can return
863prematurely from the function. It's easy to forget to free the allocated memory
864block when taking this premature exit, especially when it is added later to the
865code. Such leaks, once introduced, often go undetected for a long time: the
866error exit is taken only in a small fraction of all calls, and most modern
867machines have plenty of virtual memory, so the leak only becomes apparent in a
868long-running process that uses the leaking function frequently. Therefore, it's
869important to prevent leaks from happening by having a coding convention or
870strategy that minimizes this kind of errors.
871
Georg Brandl60203b42010-10-06 10:11:56 +0000872Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a
Georg Brandl116aa622007-08-15 14:28:22 +0000873strategy to avoid memory leaks as well as the use of freed memory. The chosen
874method is called :dfn:`reference counting`. The principle is simple: every
875object contains a counter, which is incremented when a reference to the object
876is stored somewhere, and which is decremented when a reference to it is deleted.
877When the counter reaches zero, the last reference to the object has been deleted
878and the object is freed.
879
880An alternative strategy is called :dfn:`automatic garbage collection`.
881(Sometimes, reference counting is also referred to as a garbage collection
882strategy, hence my use of "automatic" to distinguish the two.) The big
883advantage of automatic garbage collection is that the user doesn't need to call
Georg Brandl60203b42010-10-06 10:11:56 +0000884:c:func:`free` explicitly. (Another claimed advantage is an improvement in speed
Georg Brandl116aa622007-08-15 14:28:22 +0000885or memory usage --- this is no hard fact however.) The disadvantage is that for
886C, there is no truly portable automatic garbage collector, while reference
Georg Brandl60203b42010-10-06 10:11:56 +0000887counting can be implemented portably (as long as the functions :c:func:`malloc`
888and :c:func:`free` are available --- which the C Standard guarantees). Maybe some
Georg Brandl116aa622007-08-15 14:28:22 +0000889day a sufficiently portable automatic garbage collector will be available for C.
890Until then, we'll have to live with reference counts.
891
892While Python uses the traditional reference counting implementation, it also
893offers a cycle detector that works to detect reference cycles. This allows
894applications to not worry about creating direct or indirect circular references;
895these are the weakness of garbage collection implemented using only reference
896counting. Reference cycles consist of objects which contain (possibly indirect)
897references to themselves, so that each object in the cycle has a reference count
898which is non-zero. Typical reference counting implementations are not able to
899reclaim the memory belonging to any objects in a reference cycle, or referenced
900from the objects in the cycle, even though there are no further references to
901the cycle itself.
902
Georg Brandla4c8c472014-10-31 10:38:49 +0100903The cycle detector is able to detect garbage cycles and can reclaim them.
904The :mod:`gc` module exposes a way to run the detector (the
Serhiy Storchaka0b68a2d2013-10-09 13:26:17 +0300905:func:`~gc.collect` function), as well as configuration
Georg Brandl116aa622007-08-15 14:28:22 +0000906interfaces and the ability to disable the detector at runtime. The cycle
907detector is considered an optional component; though it is included by default,
Martin Panter5c679332016-10-30 04:20:17 +0000908it can be disabled at build time using the :option:`!--without-cycle-gc` option
Georg Brandlf6945182008-02-01 11:56:49 +0000909to the :program:`configure` script on Unix platforms (including Mac OS X). If
910the cycle detector is disabled in this way, the :mod:`gc` module will not be
911available.
Georg Brandl116aa622007-08-15 14:28:22 +0000912
913
914.. _refcountsinpython:
915
916Reference Counting in Python
917----------------------------
918
919There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the
Georg Brandl60203b42010-10-06 10:11:56 +0000920incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also
Georg Brandl116aa622007-08-15 14:28:22 +0000921frees the object when the count reaches zero. For flexibility, it doesn't call
Georg Brandl60203b42010-10-06 10:11:56 +0000922:c:func:`free` directly --- rather, it makes a call through a function pointer in
Georg Brandl116aa622007-08-15 14:28:22 +0000923the object's :dfn:`type object`. For this purpose (and others), every object
924also contains a pointer to its type object.
925
926The big question now remains: when to use ``Py_INCREF(x)`` and ``Py_DECREF(x)``?
927Let's first introduce some terms. Nobody "owns" an object; however, you can
928:dfn:`own a reference` to an object. An object's reference count is now defined
929as the number of owned references to it. The owner of a reference is
Georg Brandl60203b42010-10-06 10:11:56 +0000930responsible for calling :c:func:`Py_DECREF` when the reference is no longer
Georg Brandl116aa622007-08-15 14:28:22 +0000931needed. Ownership of a reference can be transferred. There are three ways to
Georg Brandl60203b42010-10-06 10:11:56 +0000932dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`.
Georg Brandl116aa622007-08-15 14:28:22 +0000933Forgetting to dispose of an owned reference creates a memory leak.
934
935It is also possible to :dfn:`borrow` [#]_ a reference to an object. The
Georg Brandl60203b42010-10-06 10:11:56 +0000936borrower of a reference should not call :c:func:`Py_DECREF`. The borrower must
Georg Brandl116aa622007-08-15 14:28:22 +0000937not hold on to the object longer than the owner from which it was borrowed.
938Using a borrowed reference after the owner has disposed of it risks using freed
Emanuele Gaifascdfe9102017-11-24 09:49:57 +0100939memory and should be avoided completely [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000940
941The advantage of borrowing over owning a reference is that you don't need to
942take care of disposing of the reference on all possible paths through the code
943--- in other words, with a borrowed reference you don't run the risk of leaking
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +0000944when a premature exit is taken. The disadvantage of borrowing over owning is
Georg Brandl116aa622007-08-15 14:28:22 +0000945that there are some subtle situations where in seemingly correct code a borrowed
946reference can be used after the owner from which it was borrowed has in fact
947disposed of it.
948
949A borrowed reference can be changed into an owned reference by calling
Georg Brandl60203b42010-10-06 10:11:56 +0000950:c:func:`Py_INCREF`. This does not affect the status of the owner from which the
Georg Brandl116aa622007-08-15 14:28:22 +0000951reference was borrowed --- it creates a new owned reference, and gives full
952owner responsibilities (the new owner must dispose of the reference properly, as
953well as the previous owner).
954
955
956.. _ownershiprules:
957
958Ownership Rules
959---------------
960
961Whenever an object reference is passed into or out of a function, it is part of
962the function's interface specification whether ownership is transferred with the
963reference or not.
964
965Most functions that return a reference to an object pass on ownership with the
966reference. In particular, all functions whose function it is to create a new
Georg Brandl60203b42010-10-06 10:11:56 +0000967object, such as :c:func:`PyLong_FromLong` and :c:func:`Py_BuildValue`, pass
Georg Brandl116aa622007-08-15 14:28:22 +0000968ownership to the receiver. Even if the object is not actually new, you still
969receive ownership of a new reference to that object. For instance,
Georg Brandl60203b42010-10-06 10:11:56 +0000970:c:func:`PyLong_FromLong` maintains a cache of popular values and can return a
Georg Brandl116aa622007-08-15 14:28:22 +0000971reference to a cached item.
972
973Many functions that extract objects from other objects also transfer ownership
Georg Brandl60203b42010-10-06 10:11:56 +0000974with the reference, for instance :c:func:`PyObject_GetAttrString`. The picture
Georg Brandl116aa622007-08-15 14:28:22 +0000975is less clear, here, however, since a few common routines are exceptions:
Georg Brandl60203b42010-10-06 10:11:56 +0000976:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and
977:c:func:`PyDict_GetItemString` all return references that you borrow from the
Georg Brandl116aa622007-08-15 14:28:22 +0000978tuple, list or dictionary.
979
Georg Brandl60203b42010-10-06 10:11:56 +0000980The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even
Georg Brandl116aa622007-08-15 14:28:22 +0000981though it may actually create the object it returns: this is possible because an
982owned reference to the object is stored in ``sys.modules``.
983
984When you pass an object reference into another function, in general, the
985function borrows the reference from you --- if it needs to store it, it will use
Georg Brandl60203b42010-10-06 10:11:56 +0000986:c:func:`Py_INCREF` to become an independent owner. There are exactly two
987important exceptions to this rule: :c:func:`PyTuple_SetItem` and
988:c:func:`PyList_SetItem`. These functions take over ownership of the item passed
989to them --- even if they fail! (Note that :c:func:`PyDict_SetItem` and friends
Georg Brandl116aa622007-08-15 14:28:22 +0000990don't take over ownership --- they are "normal.")
991
992When a C function is called from Python, it borrows references to its arguments
993from the caller. The caller owns a reference to the object, so the borrowed
994reference's lifetime is guaranteed until the function returns. Only when such a
995borrowed reference must be stored or passed on, it must be turned into an owned
Georg Brandl60203b42010-10-06 10:11:56 +0000996reference by calling :c:func:`Py_INCREF`.
Georg Brandl116aa622007-08-15 14:28:22 +0000997
998The object reference returned from a C function that is called from Python must
999be an owned reference --- ownership is transferred from the function to its
1000caller.
1001
1002
1003.. _thinice:
1004
1005Thin Ice
1006--------
1007
1008There are a few situations where seemingly harmless use of a borrowed reference
1009can lead to problems. These all have to do with implicit invocations of the
1010interpreter, which can cause the owner of a reference to dispose of it.
1011
Georg Brandl60203b42010-10-06 10:11:56 +00001012The first and most important case to know about is using :c:func:`Py_DECREF` on
Georg Brandl116aa622007-08-15 14:28:22 +00001013an unrelated object while borrowing a reference to a list item. For instance::
1014
1015 void
1016 bug(PyObject *list)
1017 {
1018 PyObject *item = PyList_GetItem(list, 0);
1019
Georg Brandl9914dd32007-12-02 23:08:39 +00001020 PyList_SetItem(list, 1, PyLong_FromLong(0L));
Georg Brandl116aa622007-08-15 14:28:22 +00001021 PyObject_Print(item, stdout, 0); /* BUG! */
1022 }
1023
1024This function first borrows a reference to ``list[0]``, then replaces
1025``list[1]`` with the value ``0``, and finally prints the borrowed reference.
1026Looks harmless, right? But it's not!
1027
Georg Brandl60203b42010-10-06 10:11:56 +00001028Let's follow the control flow into :c:func:`PyList_SetItem`. The list owns
Georg Brandl116aa622007-08-15 14:28:22 +00001029references to all its items, so when item 1 is replaced, it has to dispose of
1030the original item 1. Now let's suppose the original item 1 was an instance of a
1031user-defined class, and let's further suppose that the class defined a
1032:meth:`__del__` method. If this class instance has a reference count of 1,
1033disposing of it will call its :meth:`__del__` method.
1034
1035Since it is written in Python, the :meth:`__del__` method can execute arbitrary
1036Python code. Could it perhaps do something to invalidate the reference to
Georg Brandl60203b42010-10-06 10:11:56 +00001037``item`` in :c:func:`bug`? You bet! Assuming that the list passed into
1038:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a
Georg Brandl116aa622007-08-15 14:28:22 +00001039statement to the effect of ``del list[0]``, and assuming this was the last
1040reference to that object, it would free the memory associated with it, thereby
1041invalidating ``item``.
1042
1043The solution, once you know the source of the problem, is easy: temporarily
1044increment the reference count. The correct version of the function reads::
1045
1046 void
1047 no_bug(PyObject *list)
1048 {
1049 PyObject *item = PyList_GetItem(list, 0);
1050
1051 Py_INCREF(item);
Georg Brandl9914dd32007-12-02 23:08:39 +00001052 PyList_SetItem(list, 1, PyLong_FromLong(0L));
Georg Brandl116aa622007-08-15 14:28:22 +00001053 PyObject_Print(item, stdout, 0);
1054 Py_DECREF(item);
1055 }
1056
1057This is a true story. An older version of Python contained variants of this bug
1058and someone spent a considerable amount of time in a C debugger to figure out
1059why his :meth:`__del__` methods would fail...
1060
1061The second case of problems with a borrowed reference is a variant involving
1062threads. Normally, multiple threads in the Python interpreter can't get in each
1063other's way, because there is a global lock protecting Python's entire object
1064space. However, it is possible to temporarily release this lock using the macro
Georg Brandl60203b42010-10-06 10:11:56 +00001065:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using
1066:c:macro:`Py_END_ALLOW_THREADS`. This is common around blocking I/O calls, to
Georg Brandl116aa622007-08-15 14:28:22 +00001067let other threads use the processor while waiting for the I/O to complete.
1068Obviously, the following function has the same problem as the previous one::
1069
1070 void
1071 bug(PyObject *list)
1072 {
1073 PyObject *item = PyList_GetItem(list, 0);
1074 Py_BEGIN_ALLOW_THREADS
1075 ...some blocking I/O call...
1076 Py_END_ALLOW_THREADS
1077 PyObject_Print(item, stdout, 0); /* BUG! */
1078 }
1079
1080
1081.. _nullpointers:
1082
1083NULL Pointers
1084-------------
1085
1086In general, functions that take object references as arguments do not expect you
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001087to pass them ``NULL`` pointers, and will dump core (or cause later core dumps) if
1088you do so. Functions that return object references generally return ``NULL`` only
1089to indicate that an exception occurred. The reason for not testing for ``NULL``
Georg Brandl116aa622007-08-15 14:28:22 +00001090arguments is that functions often pass the objects they receive on to other
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001091function --- if each function were to test for ``NULL``, there would be a lot of
Georg Brandl116aa622007-08-15 14:28:22 +00001092redundant tests and the code would run more slowly.
1093
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001094It is better to test for ``NULL`` only at the "source:" when a pointer that may be
1095``NULL`` is received, for example, from :c:func:`malloc` or from a function that
Georg Brandl116aa622007-08-15 14:28:22 +00001096may raise an exception.
1097
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001098The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for ``NULL``
Georg Brandl60203b42010-10-06 10:11:56 +00001099pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF`
Georg Brandl116aa622007-08-15 14:28:22 +00001100do.
1101
1102The macros for checking for a particular object type (``Pytype_Check()``) don't
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001103check for ``NULL`` pointers --- again, there is much code that calls several of
Georg Brandl116aa622007-08-15 14:28:22 +00001104these in a row to test an object against various different expected types, and
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001105this would generate redundant tests. There are no variants with ``NULL``
Georg Brandl116aa622007-08-15 14:28:22 +00001106checking.
1107
1108The C function calling mechanism guarantees that the argument list passed to C
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001109functions (``args`` in the examples) is never ``NULL`` --- in fact it guarantees
Emanuele Gaifascdfe9102017-11-24 09:49:57 +01001110that it is always a tuple [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +00001111
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001112It is a severe error to ever let a ``NULL`` pointer "escape" to the Python user.
Georg Brandl116aa622007-08-15 14:28:22 +00001113
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001114.. Frank Stajano:
1115 A pedagogically buggy example, along the lines of the previous listing, would
1116 be helpful here -- showing in more concrete terms what sort of actions could
1117 cause the problem. I can't very well imagine it from the description.
Georg Brandl116aa622007-08-15 14:28:22 +00001118
1119
1120.. _cplusplus:
1121
1122Writing Extensions in C++
1123=========================
1124
1125It is possible to write extension modules in C++. Some restrictions apply. If
1126the main program (the Python interpreter) is compiled and linked by the C
1127compiler, global or static objects with constructors cannot be used. This is
1128not a problem if the main program is linked by the C++ compiler. Functions that
1129will be called by the Python interpreter (in particular, module initialization
1130functions) have to be declared using ``extern "C"``. It is unnecessary to
1131enclose the Python header files in ``extern "C" {...}`` --- they use this form
1132already if the symbol ``__cplusplus`` is defined (all recent C++ compilers
1133define this symbol).
1134
1135
Benjamin Petersonb173f782009-05-05 22:31:58 +00001136.. _using-capsules:
Georg Brandl116aa622007-08-15 14:28:22 +00001137
1138Providing a C API for an Extension Module
1139=========================================
1140
1141.. sectionauthor:: Konrad Hinsen <hinsen@cnrs-orleans.fr>
1142
1143
1144Many extension modules just provide new functions and types to be used from
1145Python, but sometimes the code in an extension module can be useful for other
1146extension modules. For example, an extension module could implement a type
1147"collection" which works like lists without order. Just like the standard Python
1148list type has a C API which permits extension modules to create and manipulate
1149lists, this new collection type should have a set of C functions for direct
1150manipulation from other extension modules.
1151
1152At first sight this seems easy: just write the functions (without declaring them
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001153``static``, of course), provide an appropriate header file, and document
Georg Brandl116aa622007-08-15 14:28:22 +00001154the C API. And in fact this would work if all extension modules were always
1155linked statically with the Python interpreter. When modules are used as shared
1156libraries, however, the symbols defined in one module may not be visible to
1157another module. The details of visibility depend on the operating system; some
1158systems use one global namespace for the Python interpreter and all extension
1159modules (Windows, for example), whereas others require an explicit list of
1160imported symbols at module link time (AIX is one example), or offer a choice of
1161different strategies (most Unices). And even if symbols are globally visible,
1162the module whose functions one wishes to call might not have been loaded yet!
1163
1164Portability therefore requires not to make any assumptions about symbol
1165visibility. This means that all symbols in extension modules should be declared
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001166``static``, except for the module's initialization function, in order to
Georg Brandl116aa622007-08-15 14:28:22 +00001167avoid name clashes with other extension modules (as discussed in section
1168:ref:`methodtable`). And it means that symbols that *should* be accessible from
1169other extension modules must be exported in a different way.
1170
1171Python provides a special mechanism to pass C-level information (pointers) from
Benjamin Petersonb173f782009-05-05 22:31:58 +00001172one extension module to another one: Capsules. A Capsule is a Python data type
Georg Brandl60203b42010-10-06 10:11:56 +00001173which stores a pointer (:c:type:`void \*`). Capsules can only be created and
Georg Brandl116aa622007-08-15 14:28:22 +00001174accessed via their C API, but they can be passed around like any other Python
1175object. In particular, they can be assigned to a name in an extension module's
1176namespace. Other extension modules can then import this module, retrieve the
Benjamin Petersonb173f782009-05-05 22:31:58 +00001177value of this name, and then retrieve the pointer from the Capsule.
Georg Brandl116aa622007-08-15 14:28:22 +00001178
Benjamin Petersonb173f782009-05-05 22:31:58 +00001179There are many ways in which Capsules can be used to export the C API of an
1180extension module. Each function could get its own Capsule, or all C API pointers
1181could be stored in an array whose address is published in a Capsule. And the
Georg Brandl116aa622007-08-15 14:28:22 +00001182various tasks of storing and retrieving the pointers can be distributed in
1183different ways between the module providing the code and the client modules.
1184
Benjamin Petersonb173f782009-05-05 22:31:58 +00001185Whichever method you choose, it's important to name your Capsules properly.
Georg Brandl60203b42010-10-06 10:11:56 +00001186The function :c:func:`PyCapsule_New` takes a name parameter
Serhiy Storchaka25fc0882019-10-30 12:03:20 +02001187(:c:type:`const char \*`); you're permitted to pass in a ``NULL`` name, but
Benjamin Petersonb173f782009-05-05 22:31:58 +00001188we strongly encourage you to specify a name. Properly named Capsules provide
1189a degree of runtime type-safety; there is no feasible way to tell one unnamed
1190Capsule from another.
1191
1192In particular, Capsules used to expose C APIs should be given a name following
1193this convention::
1194
1195 modulename.attributename
1196
Georg Brandl60203b42010-10-06 10:11:56 +00001197The convenience function :c:func:`PyCapsule_Import` makes it easy to
Benjamin Petersonb173f782009-05-05 22:31:58 +00001198load a C API provided via a Capsule, but only if the Capsule's name
1199matches this convention. This behavior gives C API users a high degree
1200of certainty that the Capsule they load contains the correct C API.
1201
Georg Brandl116aa622007-08-15 14:28:22 +00001202The following example demonstrates an approach that puts most of the burden on
1203the writer of the exporting module, which is appropriate for commonly used
1204library modules. It stores all C API pointers (just one in the example!) in an
Georg Brandl60203b42010-10-06 10:11:56 +00001205array of :c:type:`void` pointers which becomes the value of a Capsule. The header
Georg Brandl116aa622007-08-15 14:28:22 +00001206file corresponding to the module provides a macro that takes care of importing
1207the module and retrieving its C API pointers; client modules only have to call
1208this macro before accessing the C API.
1209
1210The exporting module is a modification of the :mod:`spam` module from section
1211:ref:`extending-simpleexample`. The function :func:`spam.system` does not call
Georg Brandl60203b42010-10-06 10:11:56 +00001212the C library function :c:func:`system` directly, but a function
1213:c:func:`PySpam_System`, which would of course do something more complicated in
Georg Brandl116aa622007-08-15 14:28:22 +00001214reality (such as adding "spam" to every command). This function
Georg Brandl60203b42010-10-06 10:11:56 +00001215:c:func:`PySpam_System` is also exported to other extension modules.
Georg Brandl116aa622007-08-15 14:28:22 +00001216
Georg Brandl60203b42010-10-06 10:11:56 +00001217The function :c:func:`PySpam_System` is a plain C function, declared
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001218``static`` like everything else::
Georg Brandl116aa622007-08-15 14:28:22 +00001219
1220 static int
1221 PySpam_System(const char *command)
1222 {
1223 return system(command);
1224 }
1225
Georg Brandl60203b42010-10-06 10:11:56 +00001226The function :c:func:`spam_system` is modified in a trivial way::
Georg Brandl116aa622007-08-15 14:28:22 +00001227
1228 static PyObject *
1229 spam_system(PyObject *self, PyObject *args)
1230 {
1231 const char *command;
1232 int sts;
1233
1234 if (!PyArg_ParseTuple(args, "s", &command))
1235 return NULL;
1236 sts = PySpam_System(command);
Georg Brandlc877a7c2010-11-26 11:55:48 +00001237 return PyLong_FromLong(sts);
Georg Brandl116aa622007-08-15 14:28:22 +00001238 }
1239
1240In the beginning of the module, right after the line ::
1241
Inada Naokic88fece2019-04-13 10:46:21 +09001242 #include <Python.h>
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244two more lines must be added::
1245
1246 #define SPAM_MODULE
1247 #include "spammodule.h"
1248
1249The ``#define`` is used to tell the header file that it is being included in the
1250exporting module, not a client module. Finally, the module's initialization
1251function must take care of initializing the C API pointer array::
1252
1253 PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001254 PyInit_spam(void)
Georg Brandl116aa622007-08-15 14:28:22 +00001255 {
1256 PyObject *m;
1257 static void *PySpam_API[PySpam_API_pointers];
1258 PyObject *c_api_object;
1259
Martin v. Löwis1a214512008-06-11 05:26:20 +00001260 m = PyModule_Create(&spammodule);
Georg Brandl116aa622007-08-15 14:28:22 +00001261 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001262 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001263
1264 /* Initialize the C API pointer array */
1265 PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;
1266
Benjamin Petersonb173f782009-05-05 22:31:58 +00001267 /* Create a Capsule containing the API pointer array's address */
1268 c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);
Georg Brandl116aa622007-08-15 14:28:22 +00001269
Brandt Bucher224b8aa2019-09-12 05:11:20 -07001270 if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) {
1271 Py_XDECREF(c_api_object);
1272 Py_DECREF(m);
1273 return NULL;
1274 }
1275
Martin v. Löwis1a214512008-06-11 05:26:20 +00001276 return m;
Georg Brandl116aa622007-08-15 14:28:22 +00001277 }
1278
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001279Note that ``PySpam_API`` is declared ``static``; otherwise the pointer
Martin v. Löwis1a214512008-06-11 05:26:20 +00001280array would disappear when :func:`PyInit_spam` terminates!
Georg Brandl116aa622007-08-15 14:28:22 +00001281
1282The bulk of the work is in the header file :file:`spammodule.h`, which looks
1283like this::
1284
1285 #ifndef Py_SPAMMODULE_H
1286 #define Py_SPAMMODULE_H
1287 #ifdef __cplusplus
1288 extern "C" {
1289 #endif
1290
1291 /* Header file for spammodule */
1292
1293 /* C API functions */
1294 #define PySpam_System_NUM 0
1295 #define PySpam_System_RETURN int
1296 #define PySpam_System_PROTO (const char *command)
1297
1298 /* Total number of C API pointers */
1299 #define PySpam_API_pointers 1
1300
1301
1302 #ifdef SPAM_MODULE
1303 /* This section is used when compiling spammodule.c */
1304
1305 static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;
1306
1307 #else
1308 /* This section is used in modules that use spammodule's API */
1309
1310 static void **PySpam_API;
1311
1312 #define PySpam_System \
1313 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])
1314
Benjamin Petersonb173f782009-05-05 22:31:58 +00001315 /* Return -1 on error, 0 on success.
1316 * PyCapsule_Import will set an exception if there's an error.
1317 */
Georg Brandl116aa622007-08-15 14:28:22 +00001318 static int
1319 import_spam(void)
1320 {
Benjamin Petersonb173f782009-05-05 22:31:58 +00001321 PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
1322 return (PySpam_API != NULL) ? 0 : -1;
Georg Brandl116aa622007-08-15 14:28:22 +00001323 }
1324
1325 #endif
1326
1327 #ifdef __cplusplus
1328 }
1329 #endif
1330
1331 #endif /* !defined(Py_SPAMMODULE_H) */
1332
1333All that a client module must do in order to have access to the function
Georg Brandl60203b42010-10-06 10:11:56 +00001334:c:func:`PySpam_System` is to call the function (or rather macro)
1335:c:func:`import_spam` in its initialization function::
Georg Brandl116aa622007-08-15 14:28:22 +00001336
1337 PyMODINIT_FUNC
Benjamin Peterson7c435242009-03-24 01:40:39 +00001338 PyInit_client(void)
Georg Brandl116aa622007-08-15 14:28:22 +00001339 {
1340 PyObject *m;
1341
Georg Brandl21151762009-03-31 15:52:41 +00001342 m = PyModule_Create(&clientmodule);
Georg Brandl116aa622007-08-15 14:28:22 +00001343 if (m == NULL)
Georg Brandl21151762009-03-31 15:52:41 +00001344 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001345 if (import_spam() < 0)
Georg Brandl21151762009-03-31 15:52:41 +00001346 return NULL;
Georg Brandl116aa622007-08-15 14:28:22 +00001347 /* additional initialization can happen here */
Georg Brandl21151762009-03-31 15:52:41 +00001348 return m;
Georg Brandl116aa622007-08-15 14:28:22 +00001349 }
1350
1351The main disadvantage of this approach is that the file :file:`spammodule.h` is
1352rather complicated. However, the basic structure is the same for each function
1353that is exported, so it has to be learned only once.
1354
Benjamin Petersonb173f782009-05-05 22:31:58 +00001355Finally it should be mentioned that Capsules offer additional functionality,
Georg Brandl116aa622007-08-15 14:28:22 +00001356which is especially useful for memory allocation and deallocation of the pointer
Benjamin Petersonb173f782009-05-05 22:31:58 +00001357stored in a Capsule. The details are described in the Python/C API Reference
1358Manual in the section :ref:`capsules` and in the implementation of Capsules (files
1359:file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` in the Python source
Georg Brandl116aa622007-08-15 14:28:22 +00001360code distribution).
1361
1362.. rubric:: Footnotes
1363
1364.. [#] An interface for this function already exists in the standard module :mod:`os`
1365 --- it was chosen as a simple and straightforward example.
1366
1367.. [#] The metaphor of "borrowing" a reference is not completely correct: the owner
1368 still has a copy of the reference.
1369
1370.. [#] Checking that the reference count is at least 1 **does not work** --- the
1371 reference count itself could be in freed memory and may thus be reused for
1372 another object!
1373
1374.. [#] These guarantees don't hold when you use the "old" style calling convention ---
1375 this is still found in much existing code.