When you’re exposing Rust code via FFI for consumption by other languages (C, Python via ctypes, Go via cgo, etc.), two of the biggest foot-guns are:
• Unsafe code going un-checked
• Rust panics unwinding past your ABI-boundary
Below is a concise set of “rules of thumb” and patterns you can follow to keep your FFI layer robust and predictable.
1. Keep all extern "C" functions safe to call
• Declare them as pub extern "C" fn … without unsafe.
• Internally, if you need to dereference raw pointers or call other unsafe interfaces, wrap that in a narrow unsafe { … } block.
• Document pointer preconditions in your function’s doc comments (e.g. “ptr must not be null and must point to a valid T).
#[no_mangle]
pub extern "C" fn widget_process(ptr: *mut Widget) -> ErrorCode {
// 1) catch unwinds (panics) ➡️ never let them escape
let result = std::panic::catch_unwind(|| {
// 2) narrow unsafe usage
unsafe {
let widget = &mut *ptr; // ptr must be non-null
widget.do_some_processing()?;
}
Ok::<(), WidgetError>(())
});
match result {
Ok(Ok(())) => ErrorCode::Success,
Ok(Err(e)) => e.into(), // convert domain errors to codes
Err(_) => ErrorCode::PanicDetected,
}
}
2. Never let a panic unwind across the FFI boundary
Rust’s default panic strategy is to unwind the stack. If that reaches into C code—it’s undefined behavior! You have two main strategies:
-
Abort on panic
Add to your Cargo.toml or build flags:
[profile.release]
panic = "abort"
Pros: simplest, no need for catch-unwind at every boundary.
Cons: your entire process will terminate on any panic.
-
Catch and convert
Surround your Rust logic in std::panic::catch_unwind and map panics to an error code (or NULL pointer, etc.).
Pros: caller can handle errors gracefully.
Cons: you pay a small performance overhead at each boundary.
3. Minimize and document your unsafe blocks
Whenever you write unsafe { … }:
• Keep the block as small as possible.
• In comments, state the invariants you’re relying on (e.g. “ptr is non-null and valid for writes”).
• Group unsafe operations together rather than peppering them everywhere.
unsafe {
// SAFETY: `ptr` was checked by the caller to be non-null and properly aligned
let slice = std::slice::from_raw_parts_mut(ptr, len);
for elem in slice { *elem = 0; }
}
4. Use C-friendly types only
• Primitives (u8, i32, f64, …)
• #[repr(C)] structs or POD types
• Raw pointers (*const T, *mut T)
• Opaque handles (struct MyHandle { _private: [u8; 0] })
Never expose Vec<T>, String, Option<T>, Result<T, E>, Box<T> directly over the boundary.
5. Error handling and ownership conventions
• Return an integer or enum error code.
• For functions that allocate, pair them with an explicit free function.
• Document who owns what and who must call free (or its equivalent).
// C-side
typedef enum {
WIDGET_OK = 0,
WIDGET_ERR_NULL,
WIDGET_ERR_INVALID_STATE,
WIDGET_ERR_PANICKED,
} widget_error_t;
widget_error_t widget_create(widget_handle_t** out);
void widget_destroy(widget_handle_t* handle);
Quick Checklist
[✔] All extern "C" functions are safe (no unsafe fn).
[✔] Panics are either aborted or caught with catch_unwind.
[✔] Unsafe blocks are minimal and well-documented.
[✔] Only C-ABI types cross the boundary.
[✔] Ownership / error-coding conventions are clearly documented.
With these rules in place, your Rust FFI layer will be predictable, safe to call from other languages, and immune to the “mystery crash” that happens when a panic slips through! 🚀