DEV Community

Cover image for Rust and python bindings
victor_dalet
victor_dalet

Posted on • Edited on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more