Debian Codegraph @

Doc/extending/building.rst

raw
1 .. highlight:: c
2
3 .. _building:
4
5 *****************************
6 Building C and C++ Extensions
7 *****************************
8
9 A C extension for CPython is a shared library (e.g. a ``.so`` file on Linux,
10 ``.pyd`` on Windows), which exports an *initialization function*.
11
12 To be importable, the shared library must be available on :envvar:`PYTHONPATH`,
13 and must be named after the module name, with an appropriate extension.
14 When using setuptools, the correct filename is generated automatically.
15
16 The initialization function has the signature:
17
18 .. c:function:: PyObject* PyInit_modulename(void)
19
20 It returns either a fully initialized module, or a :c:type:`PyModuleDef`
21 instance. See :ref:`initializing-modules` for details.
22
23 .. highlight:: python
24
25 For modules with ASCII-only names, the function must be named
26 :samp:`PyInit_{<name>}`, with ``<name>`` replaced by the name of the module.
27 When using :ref:`multi-phase-initialization`, non-ASCII module names
28 are allowed. In this case, the initialization function name is
29 :samp:`PyInitU_{<name>}`, with ``<name>`` encoded using Python's
30 *punycode* encoding with hyphens replaced by underscores. In Python::
31
32 def initfunc_name(name):
33 try:
34 suffix = b'_' + name.encode('ascii')
35 except UnicodeEncodeError:
36 suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
37 return b'PyInit' + suffix
38
39 It is possible to export multiple modules from a single shared library by
40 defining multiple initialization functions. However, importing them requires
41 using symbolic links or a custom importer, because by default only the
42 function corresponding to the filename is found.
43 See the *"Multiple modules in one library"* section in :pep:`489` for details.
44
45
46 .. highlight:: c
47
48 .. _install-index:
49 .. _setuptools-index:
50
51 Building C and C++ Extensions with setuptools
52 =============================================
53
54 Python 3.12 and newer no longer come with distutils. Please refer to the
55 ``setuptools`` documentation at
56 https://setuptools.readthedocs.io/en/latest/setuptools.html
57 to learn more about how build and distribute C/C++ extensions with setuptools.