首页 > 解决方案 > 如何使用 &str 和 String、本机类型和 PyResult 管理内存将值从 Rust 传递到 Python 时?

问题描述

使用 PyO3,我能够从 Rust 传递&strString类型到 Python:

#[pyfunction]
fn test_str(py: Python) -> &str {
    "this is a &str"
}

#[pyfunction]
fn test_string(py: Python) -> String {
    "this is a String".to_string()
}

Python 可以很好地调用这些:

>>> test_str(), type(test_str())
('this is a &str', <class 'str'>)
>>> test_string(), type(test_string())
('this is a String', <class 'str'>)

我也可以将它们包装成相同PyResult<&str>PyResult<String>行为。

如果有的话,我需要知道什么以及我需要采取其他步骤来确保这里的内存得到正确处理?如果我不想维护对相同字符串的引用,我是否需要告诉 GIL Strings 以便在必要时释放它们?

如果我需要做更多,我是否也需要对其他方法做同样的事情,比如当我创建一个 Rust 时struct

#[pyfunction]
fn new_thing(py: Python) -> Thing {
    Thing { foo: 1, bar: true }
}

标签: rustpyo3

解决方案


推荐阅读