【发布时间】:2022-11-09 21:11:25
【问题描述】:
我有一个预先导入的模块,我正在使用 python gil 调用一个方法,如下所示。
Python::with_gil(|py| {
let res = module.call_method1(py, "my_method", (arg1, arg2))?;
})
这将返回 rust 对象 PyObject,但返回的是 python list。我想遍历这个列表以将内部转换成我可以在 Rust 中使用的东西(它是一个 Numpy 数组的 Python 列表,我正在使用 numpy/ndarray 板条箱)。
我对如何迭代这个有点困惑。如果我尝试将cast_as 换成PyList,我会收到警告:UnsafeCell<PyObject> cannot be shared between threads safely。似乎extract 也不起作用。
如何迭代这个 PyObject?谢谢。
编辑:根据要求添加更多详细信息
如果您使用的是 python 打字系统,python 的返回值是 List[numpy.ndarray]。由于每个 numpy 数组的长度可能不同,我不能将其全部转换为 python 中的 numpy 数组并通过它。示例输出如下:
[array([214.17725372, 192.78236675, 354.27965546, 389.84558392,
0.99999297])]
我在 Rust 中尝试过的内容:
-
let pylist = res.cast_as::<PyList>(py)?;编译失败:
UnsafeCell<PyObject> cannot be shared between threads safely。 -
let pylist = res.extract::<PyList>(py)?;编译失败:
the trait 'PyClass' is not implemented for 'PyList'。请注意我在顶部有use pyo3::prelude::*;。 -
let pyany = res.extract::<Vec<PyArray1<f64>>>(py)?;编译失败:
the trait bound 'Vec<PyArray<f64, Dim<[usize; 1]>>>: pyo3::FromPyObject<'_>' is not satisfied。这个 PyArray 来自numpy板条箱。
【问题讨论】:
-
请分享您尝试过的代码。请包含一个包含您的 python 代码的最小示例。
-
更新了更多细节。 @PitaJ