Call C functions from Rust by declaring them with `extern "C"` and invoking them inside an `unsafe` block.
Use the extern keyword to declare the C function signature and unsafe to call it, ensuring the C library is linked.
extern "C" {
fn printf(format: *const i8, ...);
}
fn main() {
unsafe {
let msg = b"Hello from Rust\0";
printf(msg.as_ptr() as *const i8);
}
}
Compile with rustc main.rs -o main and link the C library if needed (e.g., -lc for standard C functions).
Calling C functions from Rust FFI lets Rust talk to code written in C, like using a specialized tool from a toolbox you didn't build yourself. You must tell Rust exactly what the C function looks like and mark the call as unsafe because Rust can't check if the C code is safe. It's like handing a raw key to a door; you know it works, but you're responsible for not breaking the lock.