我有一个结构体
#[pyclass]
pub struct DynMat {
...
}
and I have this function
#[pyfunction]
#[text_signature = "(tensor/)"]
pub fn exp<'py>(py: Python<'py>, tensor_or_scalar: &'py PyAny) -> PyResult<&'py PyAny> {
// I need to return &PyAny because I might either return PyFloat or DynMat
if let Ok(scalar) = tensor_or_scalar.cast_as::<PyFloat>() {
let scalar: &PyAny = PyFloat::new(py, scalar.extract::<f64>()?.exp());
Ok(scalar)
} else if let Ok(tensor) = tensor_or_scalar.cast_as::<PyCell<DynMat>>() {
let mut tensor:PyRef<DynMat> = tensor.try_borrow()?;
let tensor:DynMat = tensor.exp()?;
// what now? How to return tensor
}
}
问题是,我如何从期望
PyResult<&'py PyAny>
的函数中返回一个标记有pyclass
的Rust结构体?
Py::new(py, tensor)?.as_ref(py)
,我会得到“temporary value created here”和“returns a value referencing data owned by the current function”的警告信息。我该怎么确保创建的引用使用'py
的生命周期呢? - alagris