python - 在 rust-cpython 中将 Rust 结构转换为 PyObject

标签 python rust cpython python-cffi

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

我有一个用作输出的现有结构。如何将它变成 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,但它允许我传递具有命名字段作为键的数据。

关于python - 在 rust-cpython 中将 Rust 结构转换为 PyObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54140410/

相关文章:

Python ascii utf unicode

python - 代码仅显示从临时数组到二维数组的最新输入?

python - 使用 selenium python 下载图像

rust - 十进制数转十六进制字符串

python - `object in list` 的行为与 `object in dict` 不同?

python - Wtforms,多选文件上传

shell - 如何执行参数中带引号的命令?

reference - 在引用上泛化迭代器,在值上泛化迭代器

python - CPython 源 - 如何构建静态 python26.lib?

python - Python将函数闭包的名称绑定(bind)存放在哪里?