4. C와 C++ 확장 빌드하기

CPython의 C 확장은 초기화 함수를 내보내는 공유 라이브러리입니다 (예를 들어, 리눅스는 .so, 윈도우는 .pyd).

임포트 할 수 있으려면, 공유 라이브러리가 PYTHONPATH에 있어야 하며, 모듈 이름을 따라 적절한 확장자를 붙여서 이름 지어야 합니다. setuptools를 사용하면, 올바른 파일 이름이 자동으로 생성됩니다.

초기화 함수는 다음과 같은 서명을 갖습니다:

PyObject *PyInit_modulename(void)

완전히 초기화된 모듈이나 PyModuleDef 인스턴스를 반환합니다. 자세한 내용은 C 모듈 초기화을 참조하십시오.

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. setuptools로 C와 C++ 확장 빌드하기

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.