Sub topic 9
Wrapping unsafe calls in a safe API
This chapter assumes you can declare extern functions, call them in unsafe blocks, and use #[repr(C)], CString and CStr. It also assumes you know what a raw pointer is and how Drop works. Here you will turn raw declarations into a Rust API that callers cannot misuse.
What "safe" promises
A function without the unsafe keyword makes a promise: no caller, using only safe code, can trigger undefined behavior through it. This property is called soundness. The compiler cannot check it for FFI, because it cannot see inside the C library. You are the one who checks.
Your job is to find every rule the C function needs and enforce each one with types, ownership, or runtime checks. Typical rules are:
- Pointers must be non-null and point to valid, initialized memory.
- A resource must be freed exactly once, and not used after being freed.
- Memory borrowed from C must not outlive the object that owns it.
- Some objects must not be shared between threads.
If a rule cannot be enforced, the function stays unsafe and documents the rule.
Keep the raw layer private. The module boundary is the trust boundary: code outside it should never see a *mut RawCounter.
An RAII wrapper for an opaque handle
RAII means a value owns a resource and releases it in Drop. The spine's counter example uses this pattern. The C API is hypothetical, so the code below shows the Rust side only.
use std::ffi::{c_char, c_int, CStr};
use std::ptr::NonNull;
#[repr(C)]
pub struct RawCounter {
_private: [u8; 0],
}
// Assumed C API:
// counter *counter_new(void); // NULL on allocation failure
// int counter_increment(counter *);
// const char *counter_name(const counter *); // owned by the counter
// void counter_free(counter *);
unsafe extern "C" {
fn counter_new() -> *mut RawCounter;
fn counter_increment(c: *mut RawCounter) -> c_int;
fn counter_name(c: *const RawCounter) -> *const c_char;
fn counter_free(c: *mut RawCounter);
}
pub struct Counter {
raw: NonNull<RawCounter>,
}
impl Counter {
pub fn new() -> Option<Counter> {
// SAFETY: counter_new takes no arguments and returns either
// NULL or a pointer we now own.
NonNull::new(unsafe { counter_new() }).map(|raw| Counter { raw })
}
pub fn increment(&mut self) -> c_int {
// SAFETY: self.raw is non-null and live until Drop, and
// &mut self guarantees exclusive access.
unsafe { counter_increment(self.raw.as_ptr()) }
}
pub fn name(&self) -> &CStr {
// SAFETY: the C library documents that the returned string is
// valid until the counter is freed. The returned reference is
// tied to &self, so it cannot outlive the Counter.
unsafe { CStr::from_ptr(counter_name(self.raw.as_ptr())) }
}
}
impl Drop for Counter {
fn drop(&mut self) {
// SAFETY: raw came from counter_new and is freed only here.
unsafe { counter_free(self.raw.as_ptr()) }
}
}Each piece closes off one class of bug.
| Mechanism | Rule it enforces |
|---|---|
| `NonNull` plus `Option` from `new` | Null is rejected once, at creation. Later methods never check for it. |
| Private `raw` field | Callers cannot build a `Counter` from an arbitrary pointer. |
| `Drop` | The C free function runs exactly once, even on early return or panic. |
| No `Clone` or `Copy` | Two owners of one handle would mean a double free. |
| `&mut self` on `increment` | Rust's borrow rules give the C code exclusive access. |
| `&CStr` tied to `&self` | The borrowed string cannot be used after `counter_free`. |
Why the lifetime elision matters
In name(&self) -> &CStr, lifetime elision gives the result the lifetime of &self. CStr::from_ptr returns a reference with an unbounded lifetime, so nothing else ties it to the counter. The signature does that job. Reading the signature with this in mind is the habit to build: ask what the returned lifetime really depends on.
Returning String or &'static CStr here would be a mistake. A String copy is safe but costs an allocation and fails on invalid UTF-8. &'static CStr is unsound, because the string dies when the counter does.
Documenting safety with SAFETY comments
Every unsafe block should carry a // SAFETY: comment that explains why the preconditions hold at that point. Writing the comment is a check in itself. If you cannot justify the block in one or two sentences, the wrapper is probably missing an invariant.
For unsafe fn items, put the preconditions in a # Safety section of the doc comment. Callers read that section when deciding whether their call is valid.
impl Counter {
/// Takes ownership of a raw handle.
///
/// # Safety
///
/// `ptr` must come from `counter_new`, must not have been freed,
/// and must not be owned by any other `Counter` or C code that
/// will free it later.
pub unsafe fn from_raw(ptr: *mut RawCounter) -> Option<Counter> {
NonNull::new(ptr).map(|raw| Counter { raw })
}
/// Gives up ownership without freeing. The caller must later pass
/// the pointer to `from_raw` or to `counter_free`.
pub fn into_raw(self) -> *mut RawCounter {
let ptr = self.raw.as_ptr();
std::mem::forget(self);
ptr
}
}into_raw is safe because leaking is never undefined behavior. from_raw is unsafe because only the caller knows where the pointer came from. This asymmetry appears in the standard library too, in Box::into_raw and Box::from_raw.
Wrapping functions that take plain data
Not every wrapper needs a handle. The point_distance example from the layout chapter takes two pointers that are only read during the call.
#[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 {
// SAFETY: references are non-null, aligned and initialized, and
// point_distance only reads through them during the call.
unsafe { point_distance(a, b) }
}A reference coerces to a raw pointer, so no cast is needed. Rust guarantees the reference is valid for the whole call, and *const in the C signature tells you C does not write through it. If the C function kept the pointer for later, this wrapper would be unsound, and you would need a different design.
Choosing between safe and unsafe
Ask three questions about each C function.
- Can all its preconditions be expressed as types? If yes, make the wrapper safe.
- Do some preconditions depend on values the type system cannot see, such as "index must be below the length the C side stored"? Check them at runtime and return
ResultorOption, or panic. - Does it depend on facts outside your crate, such as pointer provenance? Keep it
unsafeand document it.
A safe wrapper that panics on a bad argument is acceptable. A safe wrapper that passes a bad argument to C is not.
Threads: Send and Sync
NonNull<T> is neither Send nor Sync, so Counter is neither by default. This is the safe default, because many C libraries use global state or thread-local state. If the library's documentation says a handle can move between threads, opt in with an unsafe impl.
// SAFETY: the C library documents that a counter may be used from any
// single thread at a time, and Counter has no shared interior state.
unsafe impl Send for Counter {}Do not implement Sync unless the library states that concurrent calls on one handle are safe. Even with &self methods, concurrent C calls may mutate hidden state. When in doubt, add neither.
Common mistakes
- Deriving
Cloneon a wrapper. A derivedClonecopies the pointer, and both copies free it inDrop. If cloning is a real need, call a C copy function in a manualCloneimpl. - Freeing in a method instead of
Drop. Aclose(self)method is fine as a convenience, butDropmust remain the backstop for early returns. - Exposing the raw pointer in a public field or a safe getter. A safe
as_ptr(&self)is acceptable, because creating a pointer is safe. Document that it is valid only while the wrapper lives, and never offer a safe way to turn a pointer back into an owner. - Panicking in
Drop. A panic during unwinding aborts the process. Log or ignore failures from the C free function. - Assuming a
&mutmethod needs no lock.&mut selfstops aliasing within Rust only. If C also holds the pointer in another structure, the wrapper cannot guarantee exclusivity.
Summary of the pattern
- Declare raw functions in a private
unsafe externblock. - Wrap each owned C resource in a struct with a private
NonNullfield. - Reject null once, in the constructor, by returning
OptionorResult. - Free the resource in
Drop, and do not implementCloneorCopy. - Tie borrowed C data to
&selfthrough return lifetimes. - Write a
// SAFETY:comment on every block and a# Safetysection on everyunsafe fn. - Implement
SendorSynconly after reading the library's threading rules.
Exercise
A colleague adds #[derive(Clone)] to Counter so that counters can be copied easily. The code compiles. What goes wrong at runtime, and what are two correct ways to support copying?
Show answer
The derived Clone copies the NonNull pointer, so two Counter values own the same C object. When both are dropped, counter_free runs twice on the same pointer, which is a double free and undefined behavior. A correct fix is a manual Clone impl that calls a C copy or duplicate function and wraps the new handle, returning a separate allocation. The other fix is to leave Counter without Clone and have callers share it through Rc or Arc, which gives shared ownership of a single handle and a single free.
Exercise
The C function const char counter_name(const counter c) returns a string owned by the counter. Why is pub fn name(&self) -> &'static CStr unsound, and what signature fixes it?
Show answer
'static claims the string lives for the whole program, but the string is freed when the Counter is dropped. Safe code could keep the &'static CStr, drop the counter, and read freed memory. The fixed signature is pub fn name(&self) -> &CStr. Lifetime elision ties the returned reference to the borrow of self, so the borrow checker rejects any use after the counter is dropped.