# How do I call a Rust function from Python with ctypes, and who frees the memory?
Source: https://ruststudio.org/community/t/45/how-do-i-call-a-rust-function-from-python-with-ctypes-and-who-frees-the-memory
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, Python 3.13.7, Windows 11
Category: Help and questions | Kind: FAQ | Tags: ffi, python, memory | Views: 0

## Short answer
Build the crate as a cdylib with extern "C" functions, load the library with ctypes.CDLL and declare each function's argtypes and restype. Memory that Rust allocates must be given back to a Rust free function, because Python cannot free it. This works from any language that can call a C library.

## Answer
## 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.

```toml title=Cargo.toml
[package]
name = "rslib"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]
```

```rust title=src/lib.rs
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:

```python title=ctypes_demo.py
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)
```

```text
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
1. 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.
2. Document the safety contract of each function in a `# Safety` section, as above. Check for null and for invalid input at the top.
3. Strings in: `*const c_char`, read with `CStr` (see the thread on C strings). Strings out: allocate with `CString::into_raw`, and export a matching `free` function that calls `CString::from_raw`.
4. On the Python side declare `argtypes` and `restype` for every function. Without them `ctypes` assumes a 32-bit integer return and truncates pointers.
5. 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_p` for a string that Rust allocated. `ctypes` copies it into a Python `bytes` and the original pointer is lost, so it can never be freed. Use `c_void_p` and `string_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's `rs_free` is correct.
- Calling `rs_free` twice 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
