Rust Systems & Tokio (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
How does Foreign Function Interface (FFI) work between Rust and C?
senior LevelCode ExampleTypeScript
In Simple Words: Allows calling C libraries from Rust and exposing Rust libraries to C/Python/Node.js:
rust
// Calling C standard library 'puts' from Rust:
extern "C" {
fn puts(s: *const std::os::raw::c_char) -> std::os::raw::c_int;
}
fn main() {
let msg = std::ffi::CString::new("Hello from C FFI").unwrap();
unsafe {
puts(msg.as_ptr());
}
}
- Uses
#[no_mangle]andextern "C"to preserve C ABI naming conventions.