The user wants me to cover "Rust FFI safely: ownership boundaries, error mapping, ABI tests."
This is a technical request about Foreign Function Interface (FFI) in the Rust programming language.
It touches on three specific sub-topics:
- Ownership Boundaries: How to manage memory safely across the Rust/C++ (or other language) divide. Who allocates, who frees? How to prevent leaks and use-after-free.
- Error Mapping: How to translate Rust's
Result<T, E> into something C (or the caller) can understand (usually integer error codes or out-parameters).
- ABI Tests: How to ensure the binary interface is correct and stable (checking struct layout, function signatures).
This is a standard programming query. It does not appear to be malicious.
It does not ask for a chain of thought or internal system prompts.
It does not violate safety guidelines.
My plan is to structure the response clearly around the three requested topics.
1. Ownership Boundaries:
- Explain the concept of "who owns the data."
- Distinguish between passing simple types (primitives) vs. complex types (pointers/structs).
- Techniques:
- "Caller allocates, caller frees" (passing buffers).
- "Callee allocates, caller frees" (returning opaque pointers).
- Using
Box and into_raw/from_raw.
- Reference counting (if applicable, but usually overkill for basic FFI).
std::mem::ManuallyDrop for safety.
- Mention types like
CString and CStr.
2. Error Mapping:
- Problem: C doesn't have
Result.
- Solution 1: Integer return codes (0 for success, non-zero for error).
- Solution 2: Out-parameters for the actual return value.
- Solution 3: "Two-phase" initialization or a global error state (like
errno or get_last_error), though less idiomatic in modern design.
- Example code showing
match on a result and converting to an error code.
- Mention
thiserror or generic error enums.
3. ABI Tests:
- Why? Because padding, alignment, and sizes differ.
- Tools:
cbindgen (generating C headers from Rust) to ensure consistency.
ctest crate (specifically for testing FFI compatibility).
#[repr(C)] (crucial for struct layout).
- Static assertions (
std::mem::size_of, std::mem::align_of).
- Unit testing the FFI layer from the Rust side (mocking C calls or compiling a C test harness).
Structure:
- Introduction: The challenge of safe FFI.
- Section 1: Managing Ownership (The "Opaque Pointer" pattern is usually the safest bet).
- Section 2: Handling Errors (Error codes + Out params).
- Section 3: Testing the ABI (Static asserts +
ctest).
- Conclusion/Summary.
I will write out the response following this structure, using Rust code snippets to illustrate.
Writing safe Foreign Function Interface (FFI) code in Rust requires strict discipline. Unlike standard Rust, the compiler cannot verify memory safety across the FFI boundary. You must manually uphold invariants.
Here is a guide to handling Ownership Boundaries, Error Mapping, and ABI Tests.
1. Ownership Boundaries
The golden rule of FFI is: Memory is owned by the allocator that allocated it.
If C allocates memory, C must free it. If Rust allocates memory, Rust must free it. Crossing this boundary unsafely leads to double-frees or use-after-free bugs.
The "Opaque Pointer" Pattern (The Safest Abstraction)
The most robust way to pass Rust objects to C is via opaque pointers. You expose a constructor, a destructor, and methods taking a raw pointer.
Rust Side:
use std::ffi::{c_void, c_char, CString};
// 1. Define a struct that represents your state
pub struct Database {
path: String,
connected: bool,
}
// 2. Constructor: Allocates memory and returns raw pointer
#[no_mangle]
pub extern "C" fn db_new(path: *const c_char) -> *mut Database {
// Unsafe block to interact with C strings
let path_str = unsafe {
std::ffi::CStr::from_ptr(path).to_str().unwrap()
};
// Allocate on heap
let db = Box::new(Database {
path: path_str.to_owned(),
connected: false,
});
// Convert Box to raw pointer, transferring ownership to caller
// (though caller must return it to us to free)
Box::into_raw(db)
}
// 3. Method: Borrows the object immutably
#[no_mangle]
pub extern "C" fn db_is_connected(db: *const Database) -> bool {
assert!(!db.is_null());
// Unsafe block to dereference the pointer
unsafe { &*db }.connected
}
// 4. Destructor: Takes ownership back and drops
#[no_mangle]
pub extern "C" fn db_free(db: *mut Database) {
if db.is_null() { return; }
// Re-construct Box to take ownership so Rust drops it automatically
unsafe { drop(Box::from_raw(db)); }
}
Rules for Safety:
Box::into_raw: Prevents Rust from running the destructor. You are handing responsibility to C.
Box::from_raw: critical in the destructor. Only call this once to reclaim ownership so Rust can free the memory.
2. Error Mapping
Rust uses Result<T, E>; C uses integer return codes (0 for success, non-zero for error) and output parameters. You must bridge these two paradigms.
Strategy: Integer Codes + Out Parameters
Instead of returning a complex struct, return an i32 status code and write the actual result to a pointer provided by the caller.
use std::ffi::{c_int, c_char, CString};
#[repr(C)]
pub enum ErrorCode {
Success = 0,
NullPointer = 1,
InvalidInput = 2,
InternalError = 3,
}
// Helper to convert Result to C-compatible tuple
fn handle_result<T>(res: Result<T, String>, out: *mut T) -> c_int {
match res {
Ok(val) => {
if !out.is_null() {
unsafe { *out = val; }
}
ErrorCode::Success as c_int
}
Err(e) => {
// In a real app, you might log `e` here or store it in a thread-local
ErrorCode::InternalError as c_int
}
}
}
// Example FFI function
#[no_mangle]
pub extern "C" fn db_get_path(db: *const Database, out_path: *mut *mut c_char) -> c_int {
if db.is_null() || out_path.is_null() {
return ErrorCode::NullPointer as c_int;
}
let db = unsafe { &*db };
// Simulate a fallible operation
let path_res = CString::new(db.path.clone())
.map_err(|_| "Nul byte found".to_string());
match path_res {
Ok(c_str) => {
// We must allocate memory for C to read (and C must free it later!)
unsafe { *out_path = c_str.into_raw(); }
ErrorCode::Success as c_int
}
Err(_) => ErrorCode::InternalError as c_int
}
}
3. ABI Tests
How do you ensure your Rust structs actually match the C structs, or that your function signatures are correct? You use static assertions and the cbindgen tool.
A. Layout Validation (#[repr(C)])
Always mark FFI structs with #[repr(C)] to ensure C-style padding and alignment.
You can verify sizes at compile time:
#[repr(C)]
pub struct Coordinate {
x: f64,
y: f64,
}
// This fails to compile if the size doesn't match the C side (e.g., 16 bytes)
const _: () = assert!(std::mem::size_of::<Coordinate>() == 16);
// Check alignment too
const _: () = assert!(std::mem::align_of::<Coordinate>() == 8);
B. The ctest Crate
For automated testing, the ctest crate is the industry standard. It generates a C file from your Rust definitions, compiles it, and runs assertions against the Rust library.
- Add
ctest to Cargo.toml (dev-dependency).
- Create a test file in
tests/ffi.rs.
// tests/ffi.rs
use std::env;
fn main() {
// Generate the C test file
let mut cfg = ctest::TestGenerator::new();
// Include the header file where C defines these types
cfg.header("my_library.h")
// Include rust definitions
.type_name(|name, _| name.to_string())
// Check the struct layout
.struct_layout(|name, layout| {
// ctest automatically verifies offsets and sizes
layout
});
// Generate the C code and run the tests
cfg.generate("../include", "target/ctest")
.expect("Failed to generate C tests");
}
C. Manual "Smoke Tests" with Miri
If you are passing raw pointers, run your tests under Miri (a tool for detecting Undefined Behavior). Miri interprets Rust bytecode and checks for memory violations that standard sanitizers might miss.
cargo +nightly miri test
Summary Checklist
- Ownership: Use
Box::into_raw to give to C, and Box::from_raw to take back. Never let Rust drop memory C owns, or vice versa.
- Error Mapping: Use
#[repr(C)] enums for error codes. Use raw pointers for "out" parameters.
- ABI: Use
cbindgen to generate headers automatically. Use ctest to verify layout matches C expectations. Use #[repr(C)] everywhere.