使用 PyO3,我能够从 Rust 传递类型到 Python &str:String
#[pyfunction]
fn test_str(py: Python) -> &str {
"this is a &str"
}
#[pyfunction]
fn test_string(py: Python) -> String {
"this is a String".to_string()
}
Run Code Online (Sandbox Code Playgroud)
Python 可以很好地调用这些:
>>> test_str(), type(test_str())
('this is a &str', <class 'str'>)
>>> test_string(), type(test_string())
('this is a String', <class 'str'>)
Run Code Online (Sandbox Code Playgroud)
我也能够将它们包装PyResult<&str>为PyResult<String>相同的行为。
我需要知道什么(如果有的话)以及需要采取其他步骤来确保内存在这里得到正确处理?如果我不想维护对相同字符串的引用,我是否需要告诉 GIL 有关 s 的信息,String以便它可以在必要时释放它们?
如果我需要做更多的事情,我是否还需要对其他方法执行相同的操作,例如当我创建 Rust 时struct?
#[pyfunction]
fn new_thing(py: Python) -> Thing {
Thing { foo: 1, bar: true }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |