How to do it...

Follow the given steps to implement this recipe:

  1. Create a file named lib.rs and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Rust-python module
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 14 April 17
//-- #########################
  1. Import the cpython library and the corresponding module:
        #[macro_use] extern crate cpython;

use cpython::{Python, PyResult};
  1. 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)
}
  1. 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(())
});
  1. Create the test.py file outside the src directory, which is the Python code:
        import example

# Running the Rust module
print(example.fibo(4))
  1. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.113.163