Call C functions in Rust by declaring them with extern "C" and invoking them inside an unsafe block.
You call C functions from Rust by declaring the external function with extern "C" and then invoking it within an unsafe block. This tells the Rust compiler to use C calling conventions and disables safety checks for the interaction.
extern "C" {
fn printf(format: *const i8, ...) -> i32;
}
fn main() {
unsafe {
let c_str = b"Hello\0";
printf(c_str.as_ptr() as *const i8);
}
}
Calling C functions from Rust lets your safe Rust code talk to older, unsafe C code. You declare the C function's name and shape so Rust knows how to call it, then you wrap the actual call in a special 'unsafe' zone. Think of it like using a translator to speak to someone who doesn't speak your language; you need the translator (the declaration) and you must be careful not to step into traffic (the unsafe block).