4

Using PyO3, I am able to pass &str and String types from Rust to 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()
}

And Python is able to call these fine:

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

I am also able to wrap these as PyResult<&str> and PyResult<String> with the same behavior.

What, if anything, do I need to know and other steps do I need to take to make sure the memory is handled properly here? If I'm not trying to maintain references to the same strings, do I need to tell the GIL about the Strings so it can free them when necessary?

If I need to do more, do I also need to do the same for other methods, such as when I create a Rust struct?

#[pyfunction]
fn new_thing(py: Python) -> Thing {
    Thing { foo: 1, bar: true }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user655321
  • 1,572
  • 2
  • 16
  • 33

0 Answers0