Sub topic 10
Calling C functions with extern blocks
This chapter assumes you know safe Rust ownership and borrowing, how raw pointers work, and how to write an unsafe function with a safety contract. It covers how to declare C functions and call them from Rust.
Why foreign calls are unsafe
The Rust compiler checks Rust code. It cannot read a C library, so it cannot confirm that a C function respects Rust's rules about memory, types, or threads. Calling a foreign function is therefore one of the five unsafe operations. You promise the compiler that the call is sound.
Declaring a foreign function
Foreign functions are declared in an unsafe extern block. The block lists names and signatures but no bodies. The "C" string selects the C calling convention, which defines how arguments and return values move between caller and callee.
unsafe extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
// SAFETY: C's `abs` has no preconditions beyond a valid i32 argument.
let v = unsafe { abs(-3) };
println!("{v}");
}The unsafe before extern says that you vouch for the declarations inside. If the signature you write does not match the real C function, the behavior is undefined. The compiler cannot detect that mismatch. The linker only matches names.
Here abs comes from the C standard library, which Rust programs link by default on most platforms. For other libraries you tell Cargo or the compiler what to link, for example with a #[link(name = "...")] attribute.
Choosing matching types
Your Rust signature must describe the same memory layout as the C one. Use the types in std::ffi and std::os::raw, or fixed-size integers when the C side is fixed-size.
| C type | Rust type |
|---|---|
| `int` | `std::ffi::c_int` |
| `unsigned int` | `std::ffi::c_uint` |
| `double` | `f64` |
| `const char *` | `*const std::ffi::c_char` |
| `void *` | `*mut std::ffi::c_void` |
References such as &T are not a safe stand-in for C pointers that may be null or may not be aligned. Use raw pointers in the declaration.
Strings across the boundary
C strings end with a zero byte and cannot contain zero bytes inside. Rust String values are neither zero-terminated nor free of interior zeros. Use CString to build a C string and CStr to read one.
use std::ffi::{CString, c_char};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize;
}
fn main() {
let text = CString::new("hello").expect("no interior zero bytes");
// SAFETY: `text.as_ptr()` points to a valid zero-terminated string
// that stays alive for the whole call.
let n = unsafe { strlen(text.as_ptr()) };
println!("{n}");
}Keep the CString in a variable. If you write CString::new("hi").unwrap().as_ptr(), the temporary is dropped at the end of the statement and the pointer dangles.
Safe functions inside extern blocks
Recent Rust editions let you mark a declaration safe when the function has no preconditions you could violate. Callers then need no unsafe block.
unsafe extern "C" {
pub safe fn abs(input: i32) -> i32;
}
fn main() {
println!("{}", abs(-3));
}Use safe only when you have confirmed that every possible argument is fine. When in doubt, leave the default, which is unsafe.
Common errors
- Wrong signature. An
i32where C expectslong, or a missing argument, gives undefined behavior with no compiler error. - Dangling pointers. The C side keeps a pointer after the Rust owner has been dropped.
- Panics crossing the boundary. Unwinding out of Rust code that C called is a problem. Catch panics before returning to C.
- Ownership confusion. Memory allocated by C's
mallocmust be freed by C'sfree, not by Rust's allocator.
How the pieces fit
The diagram shows where your guarantees are needed.
A good pattern is to wrap each foreign call in a small safe function that prepares arguments and checks results. This keeps the unsafe surface in one place.
Exercise
Why does the code above store the result of CString::new("hello") in a variable instead of calling .as_ptr() on a temporary?
Show answer
as_ptr returns a raw pointer that does not keep the CString alive. A temporary is dropped at the end of the statement, so the pointer would dangle when C reads it, which is undefined behavior. A variable keeps the string alive until the end of its scope.
Exercise
You declare fn labs(x: i32) -> i32; for the C function long labs(long). The program compiles. Is it correct?
Show answer
No. The compiler does not compare your declaration with the C one. On platforms where long is 64 bits, the argument and return types do not match, so behavior is undefined. Use std::ffi::c_long instead.