在 2025 年 Rust ndarray 与 NumPy 互操作中,如何用 PyO3 零拷贝传递数据

解读

国内一线大厂 2025 年的算法中台普遍采用“Rust 做底层算子、Python 做编排”的混合架构。面试官抛出该题,核心想验证三点:

  1. 是否真正理解“零拷贝”在 Python 与 Rust 两侧的内存语义;
  2. 能否在 PyO3 0.22+ 的新 ABI 下正确构造 PyCapsule 并对接 numpy.ndarray 的 __array_interface__;
  3. 是否掌握 Rust 端 ndarray::ArrayViewMut 的生命周期与 GIL 的互锁关系,避免悬空指针与 data race。

题目限定“2025 年”,意味着必须回答 PyO3 的 PyBackedStr 与 numpy 2.x 的 np.str_ 差异、以及 Rust 1.80+ 的 strict_provenance 对指针溯源的要求,否则会被视为“背八股”。

知识点

  1. PyO3 0.22+ 的 PyArrayHandler trait:提供 from_data_ptr 与 to_data_ptr 两个稳定接口,取代早期 pyo3::buffer::PyBuffer 的 unsafe 转换。
  2. NumPy 2.x 的 __array_interface__ 字典格式:新增 strides: None | Tuple[int, ...] 与 mask: None 字段,必须严格对齐,否则 CPython 3.13 会在 PyArray_FromInterface 直接返回 TypeError。
  3. Rust ndarray::ArrayViewMut<'a, T, D> 的 as_ptr_mut() 与 shape()、strides() 的换算:Rust 的 stride 以 元素 为单位,NumPy 以 字节 为单位,需要 mem::size_of::<T>() 乘法。
  4. PyCapsule 生命周期管理:2025 年官方推荐的 pyo3::capsule::Capsule<'py, T> 要求实现 Drop trait,在 Python 侧 capsule.__dealloc__ 时回调 Rust 的 Arc<AtomicUsize> 做引用计数减一,实现真·零拷贝释放。
  5. GIL 与 Py_LIMITED_API:如果编译时开启 abi3-py312,则无法使用 PyArray_DATA 宏,必须走 __array_interface__ 纯字典路径,否则二进制 wheel 无法在 Conda-forge 多版本 Python 发布。

答案

步骤一:Rust 侧导出只读视图

use pyo3::prelude::*;
use ndarray::{ArrayView2, Axis};
use std::os::raw::c_int;
use std::sync::Arc;

#[pyfunction]
fn as_numpy<'py>(py: Python<'py>, src: ArrayView2<'_, f32>) -> PyResult<&'py PyAny> {
    // 1. 构造 capsule 持有 Arc,保证 Rust 内存不被提前释放
    let owner = Arc::new(src);
    let capsule = PyCapsule::new_with_destructor(
        py,
        owner.clone(),
        "rust_ndarray_view",
        move |_, _| drop(owner), // 引用计数归零才 drop
    )?;

    // 2. 计算 array interface 字典
    let shape = src.shape().iter().map(|&x| x as c_int).collect::<Vec<_>>();
    let strides = src.strides().iter().map(|&s| (s * std::mem::size_of::<f32>()) as c_int).collect::<Vec<_>>();
    let iface = pyo3::types::PyDict::new(py);
    iface.set_item("typestr", "<f4")?;   // little-endian float32
    iface.set_item("data", (src.as_ptr() as usize, false))?; // read-only
    iface.set_item("shape", shape)?;
    iface.set_item("strides", strides)?;
    iface.set_item("version", 3)?;

    // 3. 通过 numpy 内部 API 重建 ndarray,零拷贝
    let numpy_mod = py.import("numpy")?;
    let np_array: &PyAny = numpy_mod.getattr("asarray")?.call((), Some(iface))?;
    // 把 capsule 挂到 ndarray 上,防止提前 GC
    np_array.setattr("__capsule", capsule)?;
    Ok(np_array)
}

步骤二:Python 侧调用

import rust_ext  # pyo3 编译的 .so
import numpy as np

a = np.random.rand(300, 400).astype(np.float32)
view = rust_ext.as_numpy(a)  # 返回同一内存,无复制
view[0, 0] = 3.14            # 修改立刻体现在原数组

关键验证:

  • view.base is a 为 False,但 view.__array_interface__['data'][0] == a.__array_interface__['data'][0] 为 True,证明零拷贝成功。
  • 通过 psutil.Process().memory_info().rss 观察,内存占用未翻倍。

拓展思考

  1. 可写场景:若需 ArrayViewMut,必须在 Rust 侧 unsafe 块里把 &mut 提升为 *mut T,并在 capsule 的析构回调中重新借回 &mut 做 drop,否则 Miri 会报 Aliasing violation。
  2. GPU 零拷贝:2025 年 cuda.ndarray 已支持 __cuda_array_interface__ v4,Rust 侧可用 cust::memory::DeviceBox 构造同样的字典,实现 PyTorch/NumPy 与 Rust GPU 算子的无缝衔接;但需保证 PCI-E BAR 内存的页对齐,否则 NumPy 会退回到 host copy。
  3. 多线程并发:Rust 端如果通过 rayon 并行写数据,必须在 capsule 里额外放一把 RwLock<()>,并在 Python 侧获取 numpy.ndarray 后先 arr.flags.writeable = False,等 Rust 计算完成再解锁并恢复 writeable=True,否则 Python 的 PyArray_CheckWriteable 会触发 ValueError: assignment destination is read-only。