How it works...

In this recipe, we created an external library in Rust, which can be used by other foreign code. The lib.rs file inside the src folder is the entry point for packages and libraries in Rust.

In Cargo.toml, while setting up the project, we set the crate-type field as ["dylib"], which lets Cargo know the project should be compiled as a dynamic library.

In lib.rs, we created a dylib type crate and we have a double_input function, which takes an integer input and returns an integer output by doubling the given input. We can see that it's the pub keyword that allows external sources to call the function, and extern makes this function stick to the Js calling conventions. The no_mangle attribute turns off Rust's name mangling so that it is easier to link.

In the main.py file, we call the externally created double_input function build using Rust code by using the cdll unit of the ctypes Python module where we use the LoadLibrary function. We pass the location of the so(shared object) file generated after compilation of the Rust project to the LoadLibrary Python function, which in our case is located at target/debug/libdouble_input.so. On successful loading of the so file, we assign double_input as lib.double_input and call it later in the script.

In order to compile and run this program, we use the make tool and create certain rules, which are sequential steps for executing the project. We create a Makefile where we first determine the ($(shell uname),Darwin) shell for detecting the OS type to set the flags. If the OS is Darwin then EXT would be EXT := dylib; else EXT is set as so. The all rule runs target/debug/libdouble_input.$(EXT) before running the Python src/main.py. The other rule basically builds the Rust project to build the libdouble_input.so file, which is used by the Python script to run the corresponding double_input function.

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

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