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

25-c-extensions-ctypes-cffi/02-c-extension-build/README.md

markdown · 0.7 KB

# 02 · c-extension-build
 
**演示**:手写最小 CPython 扩展(`PyModuleDef` + `PyArg_ParseTuple`),用 `cc -shared` 在临时目录编译成 `.so`,再通过 `importlib` 导入并调用。
**运行**:
 
```sh
uv run python examples/25-c-extensions-ctypes-cffi/02-c-extension-build/c_extension_build.py
```
 
**预期输出**(3.12.9 / macOS):
 
```text
add(2, 3): 5
```
 
**依赖**:`cc`(Xcode Command Line Tools)。缺失时脚本打印提示并退出;测试 skip。
**注意**:macOS 需要 `-undefined dynamic_lookup`,Linux 不需要;扩展名必须匹配 `EXT_SUFFIX`,初始化函数名必须是 `PyInit_<module>`。示例产物写在 `TemporaryDirectory`,不提交 `.so`。