高级互操作
本章讲解Cython与其他语言和系统的互操作技术。高质量项目往往需要集成多种语言和库。
学习路径:CFFI集成 → C++包装 → Rust → 嵌入式Python
核心技术:
- CFFI:调用C库
- extern声明:包装C++类
- cdylib:调用Rust编译的库
22.1 CFFI集成
Section titled “22.1 CFFI集成”CFFI基础
Section titled “CFFI基础”功能说明:使用CFFI调用C库。
import cffi
ffi = cffi.FFI()ffi.cdef(""" int add(int a, int b);""")ffi.set_source("mycffi", """ int add(int a, int b) { return a + b; }""")ffi.compile()功能说明:在Cython中使用CFFI包装的C代码。
# 在Cython中使用CFFI包装的C代码cdef extern from "mycffi.h": int add(int a, int b)
cpdef int fast_add(int a, int b): return add(a, b)输出示例:
>>> from mycffi import ffi>>> ffi.verify("int add(int a, int b) { return a + b; }")>>> ffi.cast("int(*)(int,int)", lib.add_funcptr)22.2 Cython与C++
Section titled “22.2 Cython与C++”C++类包装
Section titled “C++类包装”功能说明:在Cython中包装C++类。
cdef extern from *: """ #include <string>
class Calculator { public: int add(int a, int b) { return a + b; } }; """
cdef class PyCalculator: cdef Calculator* _calc
def __cinit__(self): self._calc = new Calculator()
def __dealloc__(self): del self._calc
cpdef int add(self, int a, int b): return self._calc.add(a, b)输出示例:
>>> calc = PyCalculator()>>> calc.add(1, 2)3功能说明:包装C++ vector等模板容器。
cdef extern from "<vector>" namespace "std": cdef cppclass vector[T]: vector() except + void push_back(T) T at(int) int size()
cpdef void cpp_vector_demo(): cdef vector[int]* v = new vector[int]() v.push_back(1) v.push_back(2) print(v.size()) del v输出示例:
>>> cpp_vector_demo()222.3 Rust互操作
Section titled “22.3 Rust互操作”Rust FFI基础
Section titled “Rust FFI基础”功能说明:编译Rust为C兼容的动态库。
#[no_mangle]pub extern "C" fn add(a: i32, b: i32) -> i32 { a + b}# 编译Rust库为cdylibrustc --crate-type=cdylib -o libadd.so lib.rs内存安全桥接
Section titled “内存安全桥接”功能说明:在Cython中调用Rust编译的库。
cdef extern from "libadd.so": int add(int a, int b)
cpdef int rust_add(int a, int b): return add(a, b)输出示例:
>>> rust_add(1, 2)322.4 嵌入式Python
Section titled “22.4 嵌入式Python”C中嵌入Python
Section titled “C中嵌入Python”功能说明:在C程序中嵌入Python解释器。
#include <Python.h>
int main() { Py_Initialize(); PyRun_SimpleString("print('Hello from Python!')"); Py_Finalize(); return 0;}# 编译gcc -o main main.c -I/usr/include/python3.10 -lpython3.10Cython模块
Section titled “Cython模块”功能说明:创建可嵌入的Cython模块。
def py_function(): import sys print(f"Python version: {sys.version}") return 42功能说明:管理嵌入式Python的状态。
import sys
_state = {}
def set_global(key, value): _state[key] = value
def get_global(key, default=None): return _state.get(key, default)互操作方式对比
Section titled “互操作方式对比”| 方式 | 场景 | 复杂度 |
|---|---|---|
| CFFI | 调用C库 | 中 |
| C++ extern | 包装C++类 | 中 |
| Rust cdylib | 调用Rust库 | 高 |
| 嵌入式Python | 脚本扩展 | 高 |
- 优先使用extern声明包装C/C++
- CFFI适合简单C库包装
- Rust互操作注意内存安全边界
- 嵌入式Python注意状态隔离
- 创建简单的CFFI包装,调用C函数
- 包装C++类(Calculator、Vector等)
- 编译Rust库并在Cython中调用
- 在C程序中嵌入Python解释器
- 管理嵌入式Python的状态
- 实现跨语言错误处理