|
Boundは、pyo3 0.21で導入された構造体。
関数の引数としてPythonオブジェクトを受け取る場合は、従来のPy<T>よりBound<T>の方が良いらしい。
use pyo3::prelude::*;
#[pymodule]
mod example_pyo3 {
use pyo3::{prelude::*, types::*};
#[pyfunction]
fn my_function(arg1: &Bound<PyString>) -> PyResult<String> {
let value: &str = arg1.extract()?;
let result = format!("Hello, {}", value);
Ok(result)
}
}
Bound<T>からTのデータ型に変換するには、extractメソッドを使う。
例えばPyStringからは、&strやStringに変換することが出来る。
従来のPy<T>からBound<T>に変換するにはinto_pyobjectメソッドを使う。
use pyo3::prelude::*;
#[pymodule]
mod example_pyo3 {
use pyo3::{prelude::*, types::*};
#[pyfunction]
fn my_function2(py: Python, arg1: Py<PyString>) -> PyResult<String> {
let arg1 = arg1.into_pyobject(py)?;
let value: &str = arg1.extract()?;
let result = format!("Hello, {}", value);
Ok(result)
}
}
into_pyobjectメソッドの引数にはpyが必要なので、関数の第1引数に「py: Python」を追加しておく必要がある。
Bound<T>からPy<T>へ変換するにはunbindメソッドを使う。
use pyo3::prelude::*;
#[pymodule]
mod example_pyo3 {
use pyo3::{prelude::*, types::*};
#[pyfunction]
fn my_function3(py: Python, arg1: &str) -> PyResult<Py<PyString>> {
let result = format!("Hello, {}", arg1);
let bound_py_string = result.into_pyobject(py)?; // Bound<PyString>
let py_py_string = bound_py_string.unbind(); // Py<PyString>
Ok(py_py_string)
}
}
StringからPyStringに変換するにもinto_pyobjectメソッドを使う。
Bound<T>からPy<T>へ変換するにはintoメソッドを使うことも出来る。
#[pyfunction]
fn my_function4(py: Python, arg1: &str) -> PyResult<Py<PyString>> {
let result = format!("Hello, {}", arg1);
let bound_py_string = result.into_pyobject(py)?; // Bound<PyString>
Ok(bound_py_string.into())
}