我有一个用#[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吗?
发布于 2021-06-23 23:38:04
如果您拥有函数签名的权限,只需将其更改为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)
}https://stackoverflow.com/questions/68102645
复制相似问题