How to do it...

Follow the given steps to implement this recipe:

  1. Create a file named lib.rs and open it your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Rust Function for python
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 14 April 17
//-- #########################
  1. Create the double_input function in the Rust script with the given attributes:
        #[no_mangle]
pub extern fn double_input(input: i32) -> i32 {
input * 2
}
  1. Create the main.py file, which is the Python code:
        from ctypes import cdll
from sys import platform
if platform == 'darwin':
prefix = 'lib'
ext = 'dylib'
elif platform == 'win32':
prefix = ''
ext = 'dll'
else:
prefix = 'lib'
ext = 'so'
lib = cdll.LoadLibrary('target/debug/{}double_input
.{}'.format(prefix, ext))
double_input = lib.double_input
input = 4
output = double_input(input)
print('{} * 2 = {}'.format(input, output))

  1. Create Makefile for creating the build rules:
        ifeq ($(shell uname),Darwin)
EXT := dylib
else
EXT := so
endif

all: target/debug/libdouble_input.$(EXT)
python src/main.py

target/debug/libdouble_input.$(EXT): src/lib.rs
Cargo.toml
cargo build

clean:
rm -rf target

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.138.172.130