The aim here is to write a library in Rust and call it from Python using ctypes.
Example 1: Hello World
Cargo.toml
[package]
name = "capi1"
version = "0.1.0"
edition = "2021"
[lib]
name = "capi1"
crate-type = ["rlib", "cdylib"]
[dependencies]
lib.rs
use std::ffi::{CStr,CString};
use std::os::raw::c_char;
#[no_mangle]
pub extern "C" fn hello_world() {
println!("Hello world");
}
#[no_mangle]
pub extern "C" fn hello(s: *const c_char ) {
if s.is_null() {
eprintln!("Received null pointer");
return
}
unsafe {
match CStr::from_ptr(s).to_str() {
Ok(rust_str) => {
println!("Hello {rust_str}!!");
}
Err(e) => {
eprintln!("Failed to convert C string to Rust string: {}",e);
}
}
}
}
hello.py
import ctypes
dll = ctypes.CDLL("./libcapi1.so")
hello_world = dll.hello_world
hello_world()
hello = dll.hello
hello("world".encode())