Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

FFI with C in Rust

Reference for Rust FFI: extern C functions and blocks, #[repr(C)] layout, CString and CStr, callbacks, no_mangle exports, ownership across the boundary and panic safety.

The foreign function interface (FFI) lets Rust call C functions and lets C call Rust. It relies on the C ABI (extern "C"), data laid out like C (#[repr(C)]) and C-compatible strings (CString, CStr). Everything that crosses the boundary is unsafe, because the compiler cannot see the other side.

Calling out: declare the functions in an unsafe extern "C" block and call them inside unsafe. Calling in: define a function with extern "C" and #[unsafe(no_mangle)] (edition 2024 syntax) so C can find it by name. Linking against a C library uses #[link(name = "...")] or a build script; our runner can link only libc, which is already present.

Rust
unsafe extern "C" {
    fn abs(x: i32) -> i32;
}
println!("{}", unsafe { abs(-5) });

Try it

Rust Calling libc from Rust

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust repr(C) and callbacks (Rust standing in for C)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Borrowed versus owned C strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Type mapping

C Rust
int, unsigned, long c_int, c_uint, c_long (from std::ffi)
size_t usize
char * *mut c_char / *const c_char
void * *mut c_void
struct S by value or pointer #[repr(C)] struct S
enum #[repr(C)] or #[repr(u32)] fieldless enum
function pointer extern "C" fn(...) -> ..., wrapped in Option if it may be null
NULL pointer ptr::null() / null_mut(); Option<&T> and Option<Box<T>> have the same layout

Use fixed-width types (i32, u64) only when the C side uses int32_t and friends. Rust's default struct layout (repr(Rust)) is unspecified and may reorder fields, so never pass such a struct to C.

Usage notes

  • Ownership rule: memory must be freed by the allocator that created it. Rust-allocated data returns through Box::into_raw / from_raw or CString::into_raw / from_raw; C-allocated data goes back to C's free.
  • Panics must not unwind across the boundary. An extern "C" function that panics aborts the process (since Rust 1.81). Use catch_unwind and return an error code if you need to recover; extern "C-unwind" allows controlled unwinding.
  • Strings: C strings are NUL-terminated and have no encoding guarantee; Rust String is UTF-8 without a NUL. Always convert through CString/CStr, and use to_string_lossy for untrusted bytes.
  • Safe wrapper pattern: expose a safe Rust function that validates arguments, calls the C function in a small unsafe block and converts errors, so callers never write unsafe.
  • Variadic C functions (printf) can be declared with ... but not defined in stable Rust.
  • Generating bindings: the bindgen tool creates Rust declarations from C headers, and cbindgen creates headers from Rust code; neither runs on our runner.
  • Linking: crate-type = ["cdylib"] or "staticlib" in Cargo.toml builds libraries for C to use.