Follow the given steps to implement this recipe:
- Create a file named lib.rs and open it your text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Rust Function for python
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 14 April 17
//-- #########################
- 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
}
- 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))
- 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: