Sub topic 2
Declaring and calling C functions
This chapter assumes you know basic Rust (ownership, references, Result), can run a Cargo project, and know what unsafe means. It also assumes you can read a C prototype. You need Rust 1.82 or newer for the unsafe extern syntax used here.
The extern block
Rust cannot read C headers. You have to describe each C function to the compiler yourself, in an extern block. The block lists the function names, parameter types, and return types. The compiler trusts what you write and cannot check it against the C code.
use std::ffi::{c_char, c_int, CString};
unsafe extern "C" {
fn abs(input: c_int) -> c_int;
fn strlen(s: *const c_char) -> usize;
}
fn main() {
let n = unsafe { abs(-3) };
let s = CString::new("hello").unwrap();
let len = unsafe { strlen(s.as_ptr()) };
println!("{n} {len}");
}This program prints 3 5. Both functions come from the C standard library, which Rust programs on common platforms already link, so no extra setup is needed.
What each part means
"C"names the ABI, the calling convention for passing arguments and return values. It must match how the C function was compiled.unsafe externmarks the block as a promise from you. You are saying that every signature inside it is accurate.- The function names are looked up by symbol name at link time. They must match the C names exactly.
- Declarations have no bodies, only signatures ending in
;.
In the 2021 edition and earlier, you could write extern "C" without unsafe. The 2024 edition requires unsafe extern, because a wrong declaration is a source of undefined behavior.
Calling needs unsafe
By default, every function declared in an unsafe extern block is unsafe to call. The compiler cannot see the C code, so it cannot check that you passed valid pointers or respected the function's rules. The unsafe { ... } block marks the places where you take responsibility for that.
Keep unsafe blocks small. Put only the call inside, and explain in a comment why the arguments are valid.
Marking a function safe
Since Rust 1.82 you can write safe fn inside an unsafe extern block. Callers then need no unsafe.
use std::ffi::c_int;
unsafe extern "C" {
pub safe fn abs(input: c_int) -> c_int;
}Use this with care. Here it is wrong. abs(i32::MIN) is undefined behavior in C, so the function has a precondition that Rust cannot check. Mark a function safe only when no argument value can cause undefined behavior.
Common errors
| Mistake | Result |
|---|---|
| Signature differs from the C prototype | Undefined behavior. Often wrong values or crashes, with no compiler error. |
| Using Rust types such as `i32` or `String` where C uses `int` or `char *` | Layout may differ across platforms. Use `std::ffi` types, covered in the next chapter. |
| Passing a Rust `&str` where C expects a string | No NUL terminator. C reads past the end of the data. |
| Declaring a function that no linked library defines | Link error such as "undefined reference". |
| Declaring a variadic C function like `printf` with fixed parameters | Wrong ABI. Variadics need `...` in the declaration. |
A link error is the easy failure, because the build stops. A wrong signature is the dangerous one, because the program builds and runs.
Checking your work
Declare one function at a time and call it from a small test. Compare the result with what the C documentation promises. Once the calls work, wrap each one in a safe Rust function, which a later chapter covers.
Exercise
In the 2024 edition, what is wrong with this block, and how do you fix it? extern "C" { fn getpid() -> i32; }
Show answer
The block is missing unsafe, so it does not compile in the 2024 edition. Write unsafe extern "C" { fn getpid() -> c_int; }, using std::ffi::c_int (or libc::pid_t) instead of a hard-coded i32. Calls to getpid still need an unsafe block unless you mark it safe fn.