rust - 如何使用 &str 和 String、本机类型和 PyResult 管理内存将值从 Rust 传递到 Python 时?
问题描述
使用 PyO3,我能够从 Rust 传递&str
和String
类型到 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 String
s 以便在必要时释放它们?
如果我需要做更多,我是否也需要对其他方法做同样的事情,比如当我创建一个 Rust 时struct
?
#[pyfunction]
fn new_thing(py: Python) -> Thing {
Thing { foo: 1, bar: true }
}
解决方案
推荐阅读
- c++ - 使用模板化变量的 std::vector 时出错 INSIDE a struct INSIDE a class
- sql - SQL查询获取未被考核的员工
- c - clang 创建输出目录
- excel - 宏性能 - 删除列
- apache - 使用 htaccess,将 http 或 https 域以及任何子页面重定向到另一台服务器上的特定页面
- javascript - 如何在单击时将组件添加到 vue
- google-sheets - 如果日期和名称相互重叠,则以错误响应
- python - 如何为包含大量异常值的 ML 分类任务准备 IOT 数据?
- reactjs - 将组件作为道具传递
- postgresql - 将现有数据库导入新的 Dokku 应用程序