Into Python

Let's look at embedding Rust into Python. We'll write a function to sum up the trailing zeros in a cytpes array, built by Python. We can't link statically into Python as the interpreter is already compiled and linked, so we'll need to create a dynamic library. The Cargo.toml project reflects this:

[package]
name = "zero_count"
version = "0.1.0"
authors = ["Brian L. Troutwine <brian@troutwine.us>"]

[dependencies]

[lib]
name = "zero_count"
crate-type = ["dylib"]

The sole Rust file, src/lib.rs, has a single function in it:

#[no_mangle]
pub extern "C" fn tail_zero_count(arr: *const u16, len: usize) -> u64 {
    let mut zeros: u64 = 0;
    unsafe {
        for i in 0..len {
            zeros += (*arr.offset(i as isize)).trailing_zeros() as u64
        }
    }
    zeros
}

The ...

Get Hands-On Concurrency with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.