Supercharge Your Python Apps with Rust
Welcome to our latest exploration, where we dive into the thrilling world of combining the raw power of Rust with the versatility of Python to elevate your programming projects to unprecedented levels of efficiency and performance. In "Supercharge Your Python Apps with Rust," we embark on a journey designed to transform beginners into adept users of these two formidable languages.
Whether you're looking to boost your Python application's speed, ensure memory safety, or simply be curious about integrating Rust into your workflow, this blog is your first step towards mastering the art of leveraging Rust's capabilities within your Python projects. Dive in now to discover a step-by-step guide that demystifies the process, making it accessible and straightforward for developers of all skill levels. Don't miss out on unlocking the full potential of your applications; join us in this exciting adventure!
Creating a dynamic library in Rust and calling it from Python using Foreign Function Interface (FFI) is an exciting way to leverage Rust's performance and safety in Python applications. This tutorial will guide you through the process step-by-step, with clear examples and explanations tailored for developers.
Creating a Rust Dynamic Library
Step 1: Setting Up Your Rust Project
First, you'll need to create a new Rust library project. Open a terminal and run the following command:
cargo new --lib rust_library
cd rust_library
This command creates a new Rust library project called rust_library
and moves it into the project directory.
Step 2: Writing Your Rust Function
Open the src/
lib.rs
file and replace its contents with the following code, which defines a simple function to add two numbers:
#[no_mangle]
pub extern "C" fn add_numbers(a: i32, b: i32) -> i32 {
a + b
}
#[no_mangle]
prevents Rust from changing the name of the function during compilation, making it easier to link from Python.pub extern "C"
makes this function adhere to the C calling convention, a requirement for FFI.
Step 3: Configuring Cargo.toml
Open the Cargo.toml
file and add the following lines to create a dynamic library:
[lib]
crate-type = ["cdylib"]
This configuration tells Rust to compile the library as a C-compatible dynamic library (cdylib
).
Step 4: Building the Dynamic Library
Run the following command in your terminal:
cargo build --release
After the build completes, you'll find the dynamic library in target/release
(e.g., librust_
library.so
on Linux, rust_library.dll
on Windows, or librust_library.dylib
on macOS).
Calling Rust from Python
Step 1: Installing ctypes in Python
Ensure you have ctypes
available in your Python environment. It's included in the standard library, so you should be all set.
Step 2: Writing Python Code to Call Rust Function
Create a new Python file (e.g., call_
rust.py
) and write the following code:
from ctypes import cdll, c_int
# Load the shared library. Adjust the path as necessary.
lib = cdll.LoadLibrary("target/release/librust_library.so")
# Set the argument and return types
lib.add_numbers.argtypes = (c_int, c_int)
lib.add_numbers.restype = c_int
# Call the Rust function
result = lib.add_numbers(5, 7)
print(f"The result is: {result}")
Adjust the path to
LoadLibrary
based on your dynamic library's location and name.argtypes
andrestype
ensure Python correctly converts types between Python and Rust.
Step 3: Running Your Python Code
Run your Python script:
python call_rust.py
You should see the output:
The result is: 12
Conclusion
You've now successfully created a Rust dynamic library and called it from Python using FFI! This approach enables you to combine Rust's performance and reliability with Python's ease of use, creating powerful and efficient applications.
This tutorial serves as a basic introduction to FFI and inter-language communication. As you dive deeper, you'll encounter more complex scenarios, such as passing strings or complex data structures between Rust and Python. Each step has been designed to be as developer-friendly as possible, providing you with a solid foundation for integrating Rust and Python in your projects.
The examples for the above tutorial is referenced from : https://github.com/theArjun/learning-rust/tree/main/rust_adder
Subscribe to my newsletter
Read articles from Arjun Adhikari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Arjun Adhikari
Arjun Adhikari
I am a Django developer driven by a deep passion for coding and a relentless pursuit of problem-solving. Over the years, I've cultivated my skills in web development, specializing in crafting powerful and scalable applications using the Django framework. Every project is an exciting challenge for me, and I thrive on unraveling complex problems to create elegant and efficient solutions. My commitment to staying at the forefront of industry trends and technologies reflects my dedication to continuous learning. Whether it's building innovative features from scratch or optimizing existing code, my enthusiasm for coding is at the core of everything I do. I find joy in the journey of creating impactful and user-friendly applications, leveraging the full potential of Django in the process.