【问题标题】:PyO3 convert rust struct to PyObjectPyO3 将 rust 结构转换为 PyObject
【发布时间】:2021-06-23 15:17:34
【问题描述】:

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

#[pyclass]
pub struct A {
    ...
}

现在我有了表单的功能

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

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

【问题讨论】:

    标签: python rust pyo3


    【解决方案1】:

    如果你对函数签名有权力,你可以把它改成fn f(slf: Py&lt;Self&gt;) -&gt; A

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

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

    标有#[pyclass] 的结构将实现IntoPy&lt;PyObject&gt;,但转换方法不称为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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-09
      • 2019-06-06
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多