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.
unsafe extern "C" { fn abs(x: i32) -> i32; } println!("{}", unsafe { abs(-5) });
Try it
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.
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.
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_raworCString::into_raw/from_raw; C-allocated data goes back to C'sfree. - Panics must not unwind across the boundary. An
extern "C"function that panics aborts the process (since Rust 1.81). Usecatch_unwindand 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
Stringis UTF-8 without a NUL. Always convert throughCString/CStr, and useto_string_lossyfor untrusted bytes. - Safe wrapper pattern: expose a safe Rust function that validates arguments, calls the C function in a small
unsafeblock and converts errors, so callers never writeunsafe. - Variadic C functions (
printf) can be declared with...but not defined in stable Rust. - Generating bindings: the
bindgentool creates Rust declarations from C headers, andcbindgencreates headers from Rust code; neither runs on our runner. - Linking:
crate-type = ["cdylib"]or"staticlib"inCargo.tomlbuilds libraries for C to use.