示例工程 25-c-extensions-ctypes-cffi

25-c-extensions-ctypes-cffi/02-c-extension-build/c_extension_build.py

python · 2.0 KB

"""用 cc 编译一个最小 CPython 扩展并导入。"""
 
from __future__ import annotations
 
import importlib.util
import shutil
import subprocess
import sys
import sysconfig
import tempfile
from pathlib import Path
 
C_SOURCE = """
#define PY_SSIZE_T_CLEAN
#include <Python.h>
 
static PyObject *add(PyObject *self, PyObject *args) {
    long a, b;
    if (!PyArg_ParseTuple(args, "ll", &a, &b)) {
        return NULL;
    }
    return PyLong_FromLong(a + b);
}
 
static PyMethodDef Methods[] = {
    {"add", add, METH_VARARGS, "add two ints"},
    {NULL, NULL, 0, NULL}
};
 
static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT, "mini_ext", NULL, -1, Methods
};
 
PyMODINIT_FUNC PyInit_mini_ext(void) {
    return PyModule_Create(&module);
}
"""
 
 
def compiler_available() -> bool:
    return shutil.which("cc") is not None
 
 
def build_and_call(left: int = 2, right: int = 3) -> int:
    include = sysconfig.get_paths()["include"]
    suffix = sysconfig.get_config_var("EXT_SUFFIX") or ".so"
    with tempfile.TemporaryDirectory() as tmp:
        root = Path(tmp)
        source = root / "mini_ext.c"
        source.write_text(C_SOURCE, encoding="utf-8")
        output = root / f"mini_ext{suffix}"
        command = ["cc", "-shared", "-fPIC", "-I", include, str(source), "-o", str(output)]
        if sys.platform == "darwin":
            command.extend(["-undefined", "dynamic_lookup"])
        subprocess.run(command, check=True, capture_output=True, text=True)
        spec = importlib.util.spec_from_file_location("mini_ext", output)
        if spec is None or spec.loader is None:
            raise ImportError("cannot load built extension")
        module = importlib.util.module_from_spec(spec)
        sys.modules["mini_ext"] = module
        spec.loader.exec_module(module)
        return int(module.add(left, right))
 
 
def main() -> None:
    if not compiler_available():
        print("compiler: missing (install Xcode Command Line Tools)")
        return
    print(f"add(2, 3): {build_and_call(2, 3)}")
 
 
if __name__ == "__main__":
    main()