4. Створення розширень C і C++¶
Розширення C для CPython — це спільна бібліотека (наприклад, файл .so
у Linux, .pyd
у Windows), яка експортує функцію ініціалізації.
To be importable, the shared library must be available on PYTHONPATH
,
and must be named after the module name, with an appropriate extension.
When using setuptools, the correct filename is generated automatically.
Функція ініціалізації має сигнатуру:
It returns either a fully initialized module, or a PyModuleDef
instance. See Ініціалізація модулів C for details.
For modules with ASCII-only names, the function must be named
PyInit_<name>
, with <name>
replaced by the name of the module.
When using Багатофазова ініціалізація, non-ASCII module names
are allowed. In this case, the initialization function name is
PyInitU_<name>
, with <name>
encoded using Python’s
punycode encoding with hyphens replaced by underscores. In Python:
def initfunc_name(name):
try:
suffix = b'_' + name.encode('ascii')
except UnicodeEncodeError:
suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
return b'PyInit' + suffix
Можна експортувати кілька модулів з однієї спільної бібліотеки, визначивши кілька функцій ініціалізації. Однак для їх імпортування потрібно використовувати символічні посилання або спеціальний імпортер, оскільки за замовчуванням знайдено лише функцію, яка відповідає назві файлу. Подробиці див. у розділі «Кілька модулів в одній бібліотеці» у PEP 489.
4.1. Building C and C++ Extensions with setuptools¶
Python 3.12 and newer no longer come with distutils. Please refer to the
setuptools
documentation at
https://setuptools.readthedocs.io/en/latest/setuptools.html
to learn more about how build and distribute C/C++ extensions with setuptools.