在Linux环境中,Rust和Python可以通过多种方式实现互操作性。以下是一些常见的方法:
ctypesctypes是Python的一个外部函数库,可以用来调用动态链接库(DLL)或共享对象(SO)中的函数。Rust可以编译成C兼容的共享库,然后通过ctypes在Python中调用。
// lib.rs
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}
编译Rust代码为共享库:
cargo build --release
生成的共享库通常位于target/release/libyour_crate_name.so。
import ctypes
# 加载共享库
lib = ctypes.CDLL('./target/release/libyour_crate_name.so')
# 定义函数原型
lib.add.argtypes = (ctypes.c_int, ctypes.c_int)
lib.add.restype = ctypes.c_int
# 调用函数
result = lib.add(3, 5)
print(result) # 输出: 8
cfficffi是另一个Python库,用于调用C代码。它比ctypes更灵活,支持更多的C特性。
与上面相同,编译Rust代码为共享库。
from cffi import FFI
ffi = FFI()
# 定义C函数原型
ffi.cdef("int add(int a, int b);")
# 加载共享库
lib = ffi.dlopen('./target/release/libyour_crate_name.so')
# 调用函数
result = lib.add(3, 5)
print(result) # 输出: 8
pyo3pyo3是一个Rust库,用于创建Python模块。它允许你在Rust中直接编写Python扩展模块。
// lib.rs
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
#[pyfunction]
fn add(a: i32, b: i32) -> PyResult<i32> {
Ok(a + b)
}
#[pymodule]
fn your_crate_name(py: Python, m: &PyModule) -> PyResult<()> {
m.add_function(wrap_pyfunction!(add, m)?)?;
Ok(())
}
编译Rust代码为Python模块:
cargo build --release
生成的Python模块通常位于target/release/your_crate_name.so。
import your_crate_name
result = your_crate_name.add(3, 5)
print(result) # 输出: 8
rust-cpythonrust-cpython是另一个Rust库,用于创建Python扩展模块。它提供了类似于pyo3的功能,但有一些不同的API。
与上面相同,编译Rust代码为Python模块。
与上面相同。
选择哪种方法取决于你的具体需求和偏好。ctypes和cffi更适合在Python中调用Rust编写的C兼容函数,而pyo3和rust-cpython则更适合在Rust中直接编写Python扩展模块。