PyO3 将 rust 结构转换为 PyObject

ala*_*ris 2 python rust pyo3

我有一个简单的类,注释为#[pyclass]

#[pyclass]
pub struct A {
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个形式的函数

fn f(slf: Py<Self>) -> PyObject{
   //... some code here
   let output = A{...};
   output.to_object()   // Error: method `to_object` not found for this
}
Run Code Online (Sandbox Code Playgroud)

我应该用一些东西注释我的结构以使其派生pyo3::ToPyObject吗?

Lag*_*aer 5

如果您有权控制函数签名,则可以将其更改为fn f(slf: Py<Self>) -> A

只要有可能,我更喜欢这种方法,因为这样转换就发生在幕后。

如果您需要保持签名通用,因为您可能返回不同类型的结构,则需要调用正确的转换方法。

标记为 的结构#[pyclass]将已IntoPy<PyObject>实现,但不会调用转换方法to_object,而是调用into_py,并且它需要一个 gil 令牌。所以这就是你要做的:

fn f(slf: Py<Self>) -> PyObject {
  //... some code here
  let gil = Python::acquire_gil()?;
  let py = gil.python();
  output.into_py(py)
}
Run Code Online (Sandbox Code Playgroud)