4. Construyendo extensiones C y C++

Una extensión C para CPython es una biblioteca compartida (por ejemplo, un archivo .so en Linux, .pyd en Windows), que exporta una función de inicialización.

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.

La función de inicialización tiene la firma:

PyObject *PyInit_modulename(void)

It returns either a fully initialized module, or a PyModuleDef instance. See Inicializando módulos en 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 Inicialización multifase, 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

Es posible exportar múltiples módulos desde una única biblioteca compartida definiendo múltiples funciones de inicialización. Sin embargo, importarlos requiere el uso de enlaces simbólicos o un importador personalizado, porque de forma predeterminada solo se encuentra la función correspondiente al nombre del archivo. Consulte la sección «Múltiples módulos en una biblioteca» en PEP 489 para más detalles.

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.