Answer#
A cdylib is a native shared library with a C interface: a .dll on Windows, a .so on Linux, a .dylib on macOS. Any language that can load such a library can call it, and Python's ctypes module is the quickest way to try it, with no build step on the Python side.
Three rules keep it safe: only simple C types cross the boundary (integers, floats, pointers), the types are declared on both sides, and whoever allocates the memory frees it. This crate exports three functions: one takes a string, one takes an array, and one returns a string that Rust allocated.
[package]
name = "rslib"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]use std::ffi::{c_char, CStr, CString};
/// Number of whitespace-separated words, or -1 when `s` is null or not UTF-8.
///
/// # Safety
/// `s` must be null or a valid NUL-terminated string.
#[no_mangle]
pub unsafe extern "C" fn rs_word_count(s: *const c_char) -> i32 {
if s.is_null() {
return -1;
}
match CStr::from_ptr(s).to_str() {
Ok(t) => t.split_whitespace().count() as i32,
Err(_) => -1,
}
}
/// Sum of `len` 32-bit integers.
///
/// # Safety
/// `p` must point to `len` readable i32 values (it may be null only when `len` is 0).
#[no_mangle]
pub unsafe extern "C" fn rs_sum(p: *const i32, len: usize) -> i64 {
if len == 0 {
return 0;
}
std::slice::from_raw_parts(p, len).iter().map(|&x| x as i64).sum()
}
/// Returns an upper-cased copy that Rust allocated. The caller must give it back to `rs_free`.
///
/// # Safety
/// `s` must be null or a valid NUL-terminated string.
#[no_mangle]
pub unsafe extern "C" fn rs_upper(s: *const c_char) -> *mut c_char {
if s.is_null() {
return std::ptr::null_mut();
}
let text = CStr::from_ptr(s).to_string_lossy().to_uppercase();
match CString::new(text) {
Ok(c) => c.into_raw(),
Err(_) => std::ptr::null_mut(),
}
}
/// Frees a string returned by `rs_upper`.
///
/// # Safety
/// `p` must come from `rs_upper` and must not be freed twice.
#[no_mangle]
pub unsafe extern "C" fn rs_free(p: *mut c_char) {
if !p.is_null() {
drop(CString::from_raw(p));
}
}Build with cargo build --release; the library is target/release/rslib.dll on Windows. The Python side:
import ctypes, sys
lib = ctypes.CDLL(sys.argv[1])
lib.rs_word_count.argtypes = [ctypes.c_char_p]
lib.rs_word_count.restype = ctypes.c_int32
print(lib.rs_word_count(b"one two three"), lib.rs_word_count(None))
lib.rs_sum.argtypes = [ctypes.POINTER(ctypes.c_int32), ctypes.c_size_t]
lib.rs_sum.restype = ctypes.c_int64
arr = (ctypes.c_int32 * 4)(10, 20, 30, 2_000_000_000)
print(lib.rs_sum(arr, 4))
# the string was allocated by Rust, so it must be freed by Rust: c_char_p would copy it and lose the pointer
lib.rs_upper.argtypes = [ctypes.c_char_p]
lib.rs_upper.restype = ctypes.c_void_p
lib.rs_free.argtypes = [ctypes.c_void_p]
p = lib.rs_upper("grüße".encode("utf-8"))
print(ascii(ctypes.string_at(p).decode("utf-8")))
lib.rs_free(p)3 -1
2000000060
'GR\xdcSSE'The sum is 2000000060: it is larger than a 32-bit integer can hold, which is why rs_sum returns i64. The upper-cased grüße is GRÜSSE (the sharp s becomes SS); ascii() prints the Ü as \xdc so that the output does not depend on the console's code page.
How to do it#
- Add
crate-type = ["cdylib"]and write each exported function as#[no_mangle] pub extern "C" fn(in the 2024 edition the attribute is written#[unsafe(no_mangle)]). Use only C-compatible types. - Document the safety contract of each function in a
# Safetysection, as above. Check for null and for invalid input at the top. - Strings in:
*const c_char, read withCStr(see the thread on C strings). Strings out: allocate withCString::into_raw, and export a matchingfreefunction that callsCString::from_raw. - On the Python side declare
argtypesandrestypefor every function. Without themctypesassumes a 32-bit integer return and truncates pointers. - Never let a panic cross the boundary. Return an error code, or wrap the body in
std::panic::catch_unwind.
Common mistakes#
- Declaring
restype = ctypes.c_char_pfor a string that Rust allocated.ctypescopies it into a Pythonbytesand the original pointer is lost, so it can never be freed. Usec_void_pandstring_at, as above. - Freeing the string with Python's or C's
free. Rust's allocator and the C runtime's are not guaranteed to be the same, so only Rust'srs_freeis correct. - Calling
rs_freetwice on the same pointer.
Related questions#
Is ctypes the best way to call Rust from Python?#
It needs no build tooling and works for small C-style functions. For richer types (lists, dictionaries, exceptions) and a normal import, PyO3 is more convenient: see the thread on PyO3.
Does the same library work from C#, Java or Node.js?#
Yes, because the interface is plain C. Each of them has its own way to declare and call such functions (P/Invoke in C#, JNI or the foreign function API in Java, an addon or FFI library in Node.js). Only Python was run for this thread.
Sources#
- Python documentation,
ctypes: https://docs.python.org/3/library/ctypes.html - The Rust Reference, "Linkage" (crate types): https://doc.rust-lang.org/reference/linkage.html
- The Rustonomicon, "FFI": https://doc.rust-lang.org/nomicon/ffi.html