在 rust-cpython 中将 Rust 结构转换为 PyObject
Rust struct into PyObject in rust-cpython
我正在使用 rust-cpython 编写可在 Python 中调用的 Rust 函数。
我有一个用作输出的现有结构。如何将它变成 rust-cpython 可以理解的 PyObject?
我的结构如下所示:
struct Block {
start: i32,
stop: i32,
}
我的编译错误说我需要在我的结构上实现 ToPyObject 特性。
为了用 PyObject 类型之一表示我的结构,我决定使用 PyDict。
我查看了 rust-cpython 是如何为 HashMap 做的,我只是复制了它。
impl ToPyObject for Block {
type ObjectType = PyDict;
fn to_py_object(&self, py: Python) -> PyDict {
let dict = PyDict::new(py);
dict.set_item(py, "start", self.start).unwrap();
dict.set_item(py, "stop", self.stop).unwrap();
dict
}
}
这是一种 hack,但它允许我将命名字段作为键传递数据。
我正在使用 rust-cpython 编写可在 Python 中调用的 Rust 函数。
我有一个用作输出的现有结构。如何将它变成 rust-cpython 可以理解的 PyObject?
我的结构如下所示:
struct Block {
start: i32,
stop: i32,
}
我的编译错误说我需要在我的结构上实现 ToPyObject 特性。 为了用 PyObject 类型之一表示我的结构,我决定使用 PyDict。
我查看了 rust-cpython 是如何为 HashMap 做的,我只是复制了它。
impl ToPyObject for Block {
type ObjectType = PyDict;
fn to_py_object(&self, py: Python) -> PyDict {
let dict = PyDict::new(py);
dict.set_item(py, "start", self.start).unwrap();
dict.set_item(py, "stop", self.stop).unwrap();
dict
}
}
这是一种 hack,但它允许我将命名字段作为键传递数据。