Sub topic 3
Wrapping Unsafe Calls in a Safe Rust API
This chapter assumes basic Rust ownership, borrowing, Result, Cargo, and unsafe, plus basic C pointers and malloc/free.
Hide unsafe operations behind invariants
An FFI binding is unsafe because Rust cannot verify C's rules. A safe wrapper must check those rules before calling C. It should also make ownership explicit.
For an opaque C handle, use a private field and release it in Drop:
use std::ffi::c_int;
use std::ptr::NonNull;
#[repr(C)]
pub struct RawCounter {
_private: [u8; 0],
}
// C API: counter_new returns NULL on failure.
// counter_increment returns the new value.
// counter_free releases the handle.
unsafe extern "C" {
fn counter_new() -> *mut RawCounter;
fn counter_increment(counter: *mut RawCounter) -> c_int;
fn counter_free(counter: *mut RawCounter);
}
pub struct Counter {
raw: NonNull<RawCounter>,
}
impl Counter {
pub fn new() -> Option<Self> {
NonNull::new(unsafe { counter_new() }).map(|raw| Self { 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()) }
}
}The constructor rejects a null pointer. The private field prevents callers from constructing an invalid Counter. Drop ensures the C resource is freed exactly once.
Convert C errors into `Result`
C APIs often return a status code and write the result through an out-parameter. Translate that convention immediately:
use std::ffi::{c_char, c_int, CStr};
unsafe extern "C" {
fn parse_config(path: *const c_char, out: *mut c_int) -> c_int;
}
pub fn parse(path: &CStr) -> Result<c_int, c_int> {
let mut value = 0;
let status = unsafe { parse_config(path.as_ptr(), &mut value) };
if status == 0 {
Ok(value)
} else {
Err(status)
}
}Use CString to create a null-terminated string owned by Rust, and CStr to borrow a string supplied by C.
Callbacks and panic boundaries
C can call a Rust function through an extern "C" callback. Pass state with *mut c_void, but ensure it remains valid for the entire C call.
A panic must not unwind through C. Catch it inside the callback and return an error code instead:
use std::ffi::{c_int, c_void};
use std::panic::{catch_unwind, AssertUnwindSafe};
extern "C" fn on_item(value: c_int, data: *mut c_void) -> c_int {
let result = catch_unwind(AssertUnwindSafe(|| {
let sum = unsafe { &mut *(data as *mut i64) };
*sum += i64::from(value);
}));
if result.is_ok() { 0 } else { -1 }
}Generate and review bindings
For large headers, bindgen can generate declarations:
cargo install bindgen-cli
bindgen src/wrapper.h -o src/bindings.rsReview the generated types and functions. Then write a smaller safe wrapper around them. Do not expose generated raw pointers as your public API.
| Boundary concern | Safe-wrapper responsibility |
|---|---|
| C status code | Return `Result` or a domain-specific error |
| C-owned handle | Store it privately and free it once |
| Callback panic | Catch it before returning to C |
Exercise
Why should a safe wrapper keep a C handle private?
Show answer
Privacy prevents callers from creating invalid handles, freeing them twice, or bypassing the wrapper's ownership and lifetime rules.