FAQ - Help and questions

How do I call an existing C library from Rust, with a safe wrapper?

#ffi#c-language#unsafepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Declare the C function in an extern "C" block, call it inside unsafe, and hide that call behind a small safe Rust function that checks what C cannot. For many functions let bindgen write the declarations, and for your own C files let the cc crate compile them in build.rs. The example calls qsort with a callback.

Checked with rustc 1.93.0, Windows 11 (the cc and bindgen crates were not run; no C compiler is installed on the machine used)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

The pattern has three layers. The bottom is the raw declaration, which Rust cannot check. The middle is a safe function that makes sure the conditions the C function needs are true. The top is ordinary Rust code that never sees a pointer.

The example calls qsort from the C runtime, which every Rust program on the Windows target already links, so no C file is needed to run it. qsort is a good test because it takes a pointer, a count, an element size and a callback. It was compiled and run with rustc 1.93.0.

src/main.rsrust
use std::cmp::Ordering;
use std::ffi::c_void;

extern "C" {
    // from the C runtime that every Rust program on this target already links
    fn qsort(base: *mut c_void, n: usize, size: usize, cmp: extern "C" fn(*const c_void, *const c_void) -> i32);
}

extern "C" fn cmp_i32(a: *const c_void, b: *const c_void) -> i32 {
    // SAFETY: qsort passes pointers to two elements of the array, which we declared as i32.
    let (a, b) = unsafe { (*(a as *const i32), *(b as *const i32)) };
    match a.cmp(&b) {
        Ordering::Less => -1,
        Ordering::Equal => 0,
        Ordering::Greater => 1,
    }
}

/// The safe wrapper: callers never see a pointer.
fn c_sort(v: &mut [i32]) {
    // SAFETY: the pointer and the length come from one valid slice, and the element size is size_of::<i32>().
    unsafe { qsort(v.as_mut_ptr().cast(), v.len(), std::mem::size_of::<i32>(), cmp_i32) }
}

fn main() {
    let mut v = [5, -2, 9, 0, 3];
    c_sort(&mut v);
    println!("{v:?}");
    let mut e: [i32; 0] = [];
    c_sort(&mut e);
    println!("{e:?}");
}
text
[-2, 0, 3, 5, 9]
[]

Why the wrapper is the important part: c_sort accepts only a &mut [i32], so the pointer, the count and the element size always agree. Every unsafe block carries a SAFETY: comment that states why the call is allowed. A reviewer reads those comments instead of the whole program. (In real code you would use v.sort(). qsort is only the demonstration of the mechanism.)

How to do it#

  1. Declare the functions you need in an extern "C" block, with types that match the C header: c_int, c_char, *const T, *mut T, usize for size_t. A wrong declaration is undefined behaviour that no tool will catch, which is why generating them is better.
  2. Generate the declarations with bindgen from the C header, in build.rs or on the command line, for anything larger than a handful of functions. bindgen needs libclang. It was not run for this thread.
  3. Compile your own C files by adding the cc crate as a build dependency and calling cc::Build::new().file("src/legacy.c").compile("legacy") in build.rs. Cargo then links the result. It needs a C compiler on the build machine, and none is installed on the machine used for this thread, so this step is described from the crate documentation and was not run here.
  4. Link a prebuilt library with println!("cargo:rustc-link-lib=name") in build.rs, or #[link(name = "name")] on the extern block.
  5. Wrap each function (or group) in a safe function like c_sort. Check for null, check lengths, convert strings (see the thread on C strings), and turn error codes into Result (see the thread on error codes).
  6. Put the wrapper in its own module so that all unsafe is in one place.

Common mistakes#

  • Letting a Rust panic unwind through a C frame. Catch panics at the boundary (std::panic::catch_unwind) or avoid panicking in callbacks.
  • Passing a pointer that C keeps after the call, to a value Rust then moves or frees. If C stores it, the memory must stay in place and alive; a Box leaked on purpose, with a matching free function, is the usual approach.
  • Declaring a function with the wrong argument types because it "looks the same". Let bindgen read the header.
  • Forgetting that C code can corrupt memory. Safe Rust around it does not make the C code safe.

Does extern "C" need unsafe in the 2024 edition?#

In the 2024 edition the block is written unsafe extern "C" { ... }. The example above uses the 2021 edition spelling. Check the edition in your Cargo.toml and the compiler message if it complains.

How do I call Rust from C instead?#

Write #[no_mangle] pub extern "C" fn functions (see the thread on Rust and Python with ctypes, which exposes such functions), build the crate as cdylib or staticlib, and write the C header by hand or generate it with cbindgen.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet