Sub topic 9
Wrapping unsafe calls in a safe API
This chapter assumes you know how to declare extern functions, use #[repr(C)] structs, and reason about who owns a C allocation. It shows how to hide the unsafe calls behind types that callers cannot misuse.
What "safe" means here
A function is safe to expose if no caller can trigger undefined behavior using only safe Rust. The compiler does not check this for you. You check it by hand, once, inside the wrapper. Callers then rely on your wrapper and never write unsafe themselves.
For each C function, ask what it requires and how the Rust type system can guarantee it:
| C requirement | Rust technique |
|---|---|
| Pointer is not null, aligned, and valid | Take a reference or `NonNull<T>` |
| Memory is freed exactly once | Implement `Drop` |
| No other code touches the object during a call | Take `&mut self` |
| Handle is not used after being freed | Never hand out the raw pointer by value |
Borrowing instead of pointers
The simplest wrapper turns references into pointers:
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Point {
pub x: f64,
pub y: f64,
}
unsafe extern "C" {
fn point_distance(a: *const Point, b: *const Point) -> f64;
}
pub fn distance(a: &Point, b: &Point) -> f64 {
unsafe { point_distance(a, b) }
}A Rust reference is never null, is aligned, and points to a live Point. The C function takes const pointers, so it only reads. Both conditions hold for every possible call, which makes the unsafe block sound and the outer function safe.
Owning a handle with RAII
Many C libraries give you an opaque handle that you must free. Wrap it in a struct and free it in Drop:
use std::ffi::c_int;
use std::ptr::NonNull;
#[repr(C)]
pub struct RawCounter {
_private: [u8; 0],
}
// Assumed C API: counter *counter_new(void); int counter_increment(counter *); void counter_free(counter *);
unsafe extern "C" {
fn counter_new() -> *mut RawCounter;
fn counter_increment(c: *mut RawCounter) -> c_int;
fn counter_free(c: *mut RawCounter);
}
pub struct Counter {
raw: NonNull<RawCounter>,
}
impl Counter {
pub fn new() -> Option<Counter> {
NonNull::new(unsafe { counter_new() }).map(|raw| Counter { raw })
}
pub fn increment(&mut self) -> c_int {
unsafe { counter_increment(self.raw.as_ptr()) }
}
}
impl Drop for Counter {
fn drop(&mut self) {
unsafe { counter_free(self.raw.as_ptr()) }
}
}Each part does a specific job:
NonNull::newturns a null return intoNone. EveryCounterthat exists therefore holds a non-null pointer.- The
rawfield is private, so outside code cannot replace it or free it. incrementtakes&mut self. The C function changes internal state, and Rust's exclusive borrow rules out two simultaneous calls on one handle.Dropruns exactly once when the value goes out of scope, so there is no leak and no double free.Counterdoes not implementClone. A copy would produce two owners of one C object.
Thread safety
NonNull<T> is neither Send nor Sync, so Counter is neither by default. This is the safe default, because you do not know whether the C library uses thread-local state or unsynchronized globals. Add unsafe impl Send for Counter {} only if the C documentation says the handle may move between threads.
Common mistakes
- Returning a raw pointer from a safe method, which lets callers outlive the owner.
- Adding
CloneorCopyto a type that owns a C resource. - Forgetting that
Dropalso runs after a panic in your own code. KeepDropsimple and non-panicking. - Marking a function safe because the C function "looks harmless" without checking its documented preconditions.
Exercise
In the Counter wrapper, why does increment take &mut self instead of &self, and what would go wrong if you derived Clone for Counter?
Show answer
The C function mutates the object, so &mut self uses Rust's exclusivity rule to prevent two overlapping calls on the same handle. Deriving Clone would copy the raw pointer, creating two owners. Both would run Drop and call counter_free on the same pointer, a double free.