Skip to content

Instantly share code, notes, and snippets.

@yezz123
Created December 30, 2023 13:58
Show Gist options
  • Save yezz123/4452299a995d092a6eb2e78f04c96e1a to your computer and use it in GitHub Desktop.
Save yezz123/4452299a995d092a6eb2e78f04c96e1a to your computer and use it in GitHub Desktop.
  • Compile the Rust code to a shared library:
rustc --crate-type cdylib lib.rs

the Rust code defines a simple function perform_calculation that multiplies an input integer by 2.

The Rust code is compiled into a shared library, and then the Python script loads and calls this Rust function using ctypes.

// lib.rs
#[no_mangle]
pub extern "C" fn perform_calculation(input: i32) -> i32 {
input * 2
}
import ctypes
# Load the Rust shared library
rust_lib = ctypes.CDLL('./lib.so')
# Define the input type and return type for the Rust function
rust_lib.perform_calculation.argtypes = [ctypes.c_int]
rust_lib.perform_calculation.restype = ctypes.c_int
# Call the Rust function from Python
input_value = 5
result = rust_lib.perform_calculation(input_value)
# Display the result
print(f"Result of the computation: {result}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment