【问题标题】:Rust struct into PyObject in rust-cpython在 rust-cpython 中将 Rust 结构放入 PyObject
【发布时间】:2019-06-06 00:21:39
【问题描述】:

我正在使用 rust-cpython 在 Rust 中编写可在 Python 中调用的函数。

我有一个用作输出的现有结构。如何将其变成 rust-cpython 可以理解的 PyObject?

我的结构如下所示:

struct Block {
    start: i32,
    stop: i32,
}

【问题讨论】:

    标签: python rust cpython python-cffi


    【解决方案1】:

    我的编译错误说我需要在我的结构上实现 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,但它允许我使用命名字段作为键传递数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-09
      • 2020-08-28
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 2022-12-03
      • 2021-05-08
      相关资源
      最近更新 更多