Follow the given steps to implement this recipe:
- Create a file named lib.rs and open it in your text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Rust-python module
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 14 April 17
//-- #########################
- Import the cpython library and the corresponding module:
#[macro_use] extern crate cpython;
use cpython::{Python, PyResult};
- Create the fibo function in the Rust language, which is an implementation of the Fibonacci sequence:
fn fibo(py: Python, n : u64) -> PyResult<u64> {
if n < 2 {
return Ok(1)
}
let mut prev1 = 1;
let mut prev2 = 1;
for _ in 1..n {
let new = prev1 + prev2;
prev2 = prev1;
prev1 = new;
}
Ok(prev1)
}
- Create the Python module interface, which exposes the fibo function to Python calls:
// To build a Python compatible module we need an
intialiser which expose the public interface
py_module_initializer!(example, initexample,
PyInit_example, |py, m| {
// Expose the function fibo as `extern "C"`
try!(m.add(py, "fibo", py_fn!(py, fibo(rand_int:
u64))));
// Initialiser's macro needs a Result<> as return value
Ok(())
});
- Create the test.py file outside the src directory, which is the Python code:
import example
# Running the Rust module
print(example.fibo(4))
- Create Makefile for creating build rules:
all: run
build:
cargo build --release
cp ./target/release/libexample.so ./example.so
run: build
python test.py
clean:
cargo clean
rm ./example.so
We will get the following output on the successful execution of our code: