4.Building C and C++ Extensions¶
A C extension for CPython is a shared library (e.g. a.so
file on Linux,.pyd
on Windows), which exports aninitialization function.
To be importable, the shared library must be available onPYTHONPATH
,and must be named after the module name, with an appropriate extension.When using setuptools, the correct filename is generated automatically.
The initialization function has the signature:
It returns either a fully initialized module, or aPyModuleDef
instance. SeeInitializing C modules for details.
For modules with ASCII-only names, the function must be namedPyInit_<name>
, with<name>
replaced by the name of the module.When usingMulti-phase initialization, non-ASCII module namesare allowed. In this case, the initialization function name isPyInitU_<name>
, with<name>
encoded using Python’spunycode encoding with hyphens replaced by underscores. In Python:
definitfunc_name(name):try:suffix=b'_'+name.encode('ascii')exceptUnicodeEncodeError:suffix=b'U_'+name.encode('punycode').replace(b'-',b'_')returnb'PyInit'+suffix
It is possible to export multiple modules from a single shared library bydefining multiple initialization functions. However, importing them requiresusing symbolic links or a custom importer, because by default only thefunction corresponding to the filename is found.See the“Multiple modules in one library” section inPEP 489 for details.
4.1.Building C and C++ Extensions with setuptools¶
Python 3.12 and newer no longer come with distutils. Please refer to thesetuptools
documentation athttps://setuptools.readthedocs.io/en/latest/setuptools.htmlto learn more about how build and distribute C/C++ extensions with setuptools.