Rustのチュートリアルを終えたばかりです。rustc 1.34.0-nightly
Pyo3の例1, 例2を実際に試して動作を確認しました。
次に自分なりに動きそうなモジュールを作ってみよう考え、入力されたBytes文字のSha256ハッシュを取りBytes文字で返す関数を書きました。しかし、試行錯誤を繰り返しましたがBytes文字で返す方法がわかりません。
Vec<u8>を返しListを取得する関数を追加して書きました(sha256hash_vec)
rust
1use pyo3::prelude::*; 2use pyo3::wrap_pyfunction; 3use pyo3::types::PyBytes; 4use sha2::{Sha256, Digest}; 5 6#[pyfunction] 7fn sha256hash_vec(byte: &PyBytes) -> PyResult<Vec<u8>> { 8 let mut hasher = Sha256::new(); 9 hasher.input(byte.as_bytes()); 10 let r = hasher.result().to_vec(); 11 Ok(r) 12} 13 14#[pyfunction] 15fn sha256hash_bytes(_py: Python, byte: &PyBytes) -> PyResult<Py<PyBytes>> { 16 let mut hasher = Sha256::new(); 17 hasher.input(byte.as_bytes()); 18 let r = hasher.result().as_slice(); 19 Ok(PyBytes::new(_py, &r)) 20 // 動かない 21} 22 23/// This module is a python module implemented in Rust. 24#[pymodule] 25fn pochash(_py: Python, m: &PyModule) -> PyResult<()> { 26 m.add_wrapped(wrap_pyfunction!(sha256hash_vec))?; 27 m.add_wrapped(wrap_pyfunction!(sha256hash_bytes))?; 28 Ok(()) 29}
error
1error[E0716]: temporary value dropped while borrowed 2 --> src\lib.rs:28:13 3 | 428 | let r = hasher.result().as_slice(); 5 | ^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement 6 | | 7 | creates a temporary which is freed while still in use 829 | Ok(PyBytes::new(_py, &r)) 9 | -- borrow later used here 10 | 11 = note: consider using a `let` binding to create a longer lived value
Users gide documentを読みましたがよくわかりませんでした。
pyfunctionアトリビュートの効果もよくわからず先へ進めない状態です。
解答の方を宜しくお願いします。
追記
一応解決はしましたが理由はわかりませんでした。まだまだ解答を受け付けたいと思います。
rust
1#[pyfunction] 2fn sha256hash_bytes(_py: Python<'_>, byte: &PyBytes) -> PyResult<Py<PyBytes>> { 3 let mut hasher = Sha256::new(); 4 hasher.input(byte.as_bytes()); 5 Ok(PyBytes::new(_py, hasher.result().as_slice())) 6}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。