DEV Community

Cover image for Rust and python bindings
victor_dalet
victor_dalet

Posted on • Edited on

Rust and python bindings

I - Install pip package


pip install maturin 
Enter fullscreen mode Exit fullscreen mode

II - Create project


maturin new --bindings pyo3 --mixed name_project 
Enter fullscreen mode Exit fullscreen mode

Image description

III - Create rust lib


Create in src matrix.rs with your code like this

use rand::Rng; pub fn generate_matrix() -> Vec<Vec<i32>> { let mut matrix = vec![]; for _ in 0..10 { let mut row = vec![]; for _ in 0..10 { row.push(rand::thread_rng().gen_range(0..100)); } matrix.push(row); } matrix } 
Enter fullscreen mode Exit fullscreen mode

In src/lib.rs add your code like this :

mod matrix; #[pyfunction] fn random_matrix() -> Vec<Vec<i32>> { matrix::generate_matrix() } 
Enter fullscreen mode Exit fullscreen mode

And functions in the python module like this :

#[pymodule] fn my_project(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(random_matrix, m)?)?; Ok(()) } 
Enter fullscreen mode Exit fullscreen mode

IV - Compile


maturin build && pip install . 
Enter fullscreen mode Exit fullscreen mode

V - Test


In python/name_project/test/ for exemple, create one file with this and run it.

import my_project matrix = my_project.random_matrix() print(matrix) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)