🦀 Rust Advanced

How does Rust FFI (Foreign Function Interface) work with C?

Answer

Rust can call C functions and be called from C using its FFI. To call C from Rust, declare an extern "C" block with the function signatures: extern "C" { fn strlen(s: *const c_char) -> usize; }. Calling these is unsafe because Rust cannot verify C's memory safety. Link the C library via build.rs (using the cc crate) or #[link(name = "mylib")]. Use #[repr(C)] on structs to ensure they have C-compatible memory layout. To expose Rust functions to C, annotate with #[no_mangle] (prevents name mangling) and extern "C": #[no_mangle] pub extern "C" fn my_func() -> i32 { 42 }. The bindgen crate auto-generates Rust FFI bindings from C header files, and cbindgen generates C headers from Rust. Always use std::ffi types (CStr, CString) for string interop.