我有一个rust结构,它使用pyclass宏来允许在pyo3中使用。这对于简单的结构很有效,但是如果我的结构包含来自不同库的类型,就会变得更加困难。
示例:
use geo::Point;
#[pyclass]
#[derive(Clone, Copy)]
pub struct CellState {
pub id: u32,
pub position: Point<f64>,
pub population: u32,
}上面我们使用了rust geo库中的Point类型。编译器提供以下错误:the trait `pyo3::PyClass` is not implemented for `geo::Point<f64>
如果我随后尝试在Point上实现PyClass:
impl PyClass for Point<f64> {}它给出了以下编译器错误:impl doesn't use only types from inside the current crate
有没有一个干净简单的方法来解决这个问题?
发布于 2021-01-27 20:58:02
在出现更好的答案之前,我的解决方案是将类嵌套在python类中,但随后我必须手动编写getter和setter。
#[pyclass]
#[derive(Clone)]
pub struct CellStatePy {
pub inner: CellState,
}
#[pymethods]
impl CellStatePy {
#[new]
pub fn new(id: u32, pos: (f64, f64), population: u32) -> Self {
CellStatePy {
inner: CellState {
id: CellIndex(id),
position: point!(x: pos.0, y: pos.1),
population,
},
}
}
}然后实现PyObjectProtocol:
#[pyproto]
impl PyObjectProtocol for CellStatePy {
fn __str__(&self) -> PyResult<&'static str> {
Ok("CellStatePy")
}
fn __repr__<'a>(&'a self) -> PyResult<String> {
Ok(format!("CellStateObj id: {:?}", self.inner.id))
}
fn __getattr__(&'a self, name: &str) -> PyResult<String> {
let out: String = match name {
"id" => self.inner.id.into(),
"position" => format!("{},{}", self.inner.position.x(), self.inner.position.y()),
"population" => format!("{}", self.inner.population),
&_ => "INVALID FIELD".to_owned(),
};
Ok(out)
}
}https://stackoverflow.com/questions/65393247
复制相似问题