We are going to design a Rust FFI example that demonstrates:
- Ownership boundaries: How to safely transfer ownership across the FFI boundary.
- Error mapping: How to map Rust errors to C-style error codes and how to propagate error information.
- ABI tests: How to write tests that ensure the FFI functions have the correct ABI and behavior.
We'll create a simple library that provides a function to compute the square of a number and a function that might fail (like division) and returns an error.
Steps:
- Define a C-compatible error type and functions.
- Implement the functions in Rust, handling errors and ownership.
- Provide a way to release resources (if any) to avoid leaks.
- Write tests that call the FFI functions (using the C ABI) to ensure they work.
Let's create:
square: takes an integer and returns its square. This doesn't fail and doesn't transfer ownership (just a copy).
safe_divide: takes two integers and returns the division result as a double. If the divisor is zero, returns an error.
For error handling, we'll define a struct that holds an error code and a message (which we'll allocate on the heap and must be freed by the caller).
However, note that in C, strings are just pointers. We have to be cautious about who allocates and who frees.
Let's define:
// In the C header (we'll write a corresponding Rust representation)
typedef struct {
int code;
const char* message;
} FfiError;
typedef struct {
double value;
FfiError error;
int has_error; // 0 for no error, 1 for error
} FfiResult;
But note: returning a struct by value in C ABI is tricky because different platforms have different rules. Instead, we can return a pointer to a heap-allocated result, and the caller must free it.
Alternatively, we can use an out-parameter pattern:
// The function will write the result to the `out` pointer and return an error code.
// If there's an error, the out value is undefined.
int safe_divide(int a, int b, double* out);
But that's not very Rust-like and doesn't convey the error message.
Let's do:
// The function returns a pointer to an FfiResult, which must be freed by ffi_result_free.
FfiResult* safe_divide(int a, int b);
And we must provide:
void ffi_result_free(FfiResult* result);
However, note that the FfiResult contains a const char* for the message, which we also allocate. We must design our Rust types so that when we free the FfiResult, we also free the message.
Alternatively, we can have:
typedef struct {
double* value; // NULL if error
FfiError* error; // NULL if no error
} FfiResult;
But then we have two allocations to free.
Let's design:
In Rust:
#[repr(C)]
pub struct FfiError {
code: i32,
message: *const c_char, // This will be allocated by Rust and must be freed by the caller using `ffi_error_free`
}
#[repr(C)]
pub struct FfiResult {
value: f64,
error: *mut FfiError, // NULL if no error, otherwise points to an FfiError
}
// We also need a way to free the FfiError and FfiResult.
But note: the caller (in C) must know to free the error if it's non-NULL, and then free the result.
Alternatively, we can combine:
#[repr(C)]
pub enum FfiResult {
Ok(f64),
Err(FfiError),
}
But enums in C ABI are not straightforward. We cannot have a Rust enum exposed directly because the representation is not guaranteed to be compatible with C.
So let's stick to the struct with an error pointer.
However, note that the C code must check if error is NULL. We can also add a has_error field for clarity, but that's redundant.
Let's do:
#[repr(C)]
pub struct FfiResult {
value: f64,
error: *mut FfiError, // if NULL, then value is valid, else error is valid.
}
But then the C code must check which one is non-NULL? Actually, we can set one to NULL and the other to a valid value.
Alternatively, we can return a union? But unions in C are not type-safe and Rust doesn't support C unions in a straightforward way for FFI.
So let's stick to:
// In C:
typedef struct {
double value;
FfiError* error; // if non-NULL, then value is undefined and error is set.
} FfiResult;
Then:
- On success:
value is set, error is NULL.
- On error:
error is set (non-NULL), value is undefined.
But note: the FfiError itself has a message which is a string. We must allocate that string in Rust and free it when FfiError is freed.
Now, the functions:
-
square doesn't fail, so we can just return an i32.
-
safe_divide returns an FfiResult.
-
We need ffi_error_free and ffi_result_free (which will free the error if present and then the result).
However, note: the FfiResult is allocated by Rust and returned as a pointer. The caller must free it with ffi_result_free, which in turn will free the error if present.
Let's implement:
In Rust:
use std::ffi::{c_char, CString};
use std::mem;
#[repr(C)]
pub struct FfiError {
code: i32,
message: *const c_char,
}
#[repr(C)]
pub struct FfiResult {
value: f64,
error: *mut FfiError,
}
// We must ensure that these structs are C-compatible.
// Function to create an FfiError from a string and code.
fn create_ffi_error(code: i32, message: &str) -> FfiError {
let c_message = CString::new(message).unwrap();
FfiError {
code,
message: c_message.into_raw(),
}
}
// We'll expose:
#[no_mangle]
pub extern "C" fn square(a: i32) -> i32 {
a * a
}
#[no_mangle]
pub extern "C" fn safe_divide(a: i32, b: i32) -> *mut FfiResult {
if b == 0 {
let error = create_ffi_error(1, "Division by zero");
let result = FfiResult {
value: 0.0, // undefined, but we set to 0 for safety.
error: Box::into_raw(Box::new(error)),
};
Box::into_raw(Box::new(result))
} else {
let result = FfiResult {
value: a as f64 / b as f64,
error: std::ptr::null_mut(),
};
Box::into_raw(Box::new(result))
}
}
#[no_mangle]
pub extern "C" fn ffi_error_free(error: *mut FfiError) {
if !error.is_null() {
unsafe {
let _ = CString::from_raw(error.message as *mut c_char);
Box::<FfiError>::from_raw(error);
}
}
}
#[no_mangle]
pub extern "C" fn ffi_result_free(result: *mut FfiResult) {
if !result.is_null() {
unsafe {
if !(*result).error.is_null() {
ffi_error_free((*result).error);
}
Box::<FfiResult>::from_raw(result);
}
}
}
However, note: in the error case, we are allocating an FfiError and storing it in the FfiResult. Then the FfiResult is allocated and returned. When freeing the FfiResult, we free the error if present.
But note: the message in FfiError is a raw pointer to a CString. When we free the FfiError, we convert that raw pointer back to a CString and drop it.
However, there's a problem: the create_ffi_error function uses CString::into_raw which transfers ownership to the raw pointer. Then when we free, we use CString::from_raw to reclaim ownership and drop it.
But note: the message field in FfiError is *const c_char, but we are storing a pointer from CString::into_raw which is *mut c_char. This is safe because CString::into_raw returns a *mut c_char but we are storing it as *const. Then when we free, we cast it back to *mut in from_raw. That's okay.
However, we must be cautious: the FfiError struct is defined with message: *const c_char but we are storing a *mut in it. That's a type mismatch. We should change FfiError to:
#[repr(C)]
pub struct FfiError {
code: i32,
message: *mut c_char, // because we are going to free it as a CString (which requires *mut)
}
Actually, CString::into_raw returns *mut c_char. So let's change to *mut c_char for consistency.
But note: the C header will have char* (which is *mut c_char in Rust) or const char*? We want the C code to treat it as a const string (it shouldn't modify it). However, when freeing, we need to pass it to CString::from_raw which requires *mut. So we have two options:
Option 1: In C, we declare it as const char* and in Rust we use *mut c_char and then when freeing, we cast to *mut (which is safe because we know it's a CString). But then the C code sees a const char* and Rust stores a *mut. That's okay because we are not going to let C modify it.
Option 2: In C, we declare it as char* and the C code must not modify it. But then we lose the const.
Let's go with Option 1: in the C header we have const char*, and in Rust we have *mut c_char for the field. Then when we create the CString, we get a *mut c_char and store it. When we free, we cast it back to *mut (which it already is) and then use from_raw.
Actually, the type of message in FfiError should be *mut c_char to match the return of CString::into_raw. But then the C code will see a const char*? No, the C code will see the type we define in the C header. We are generating the Rust code and the C header separately. We must make sure the C header matches the Rust representation.
Let's design the C header:
// ffi.h
#ifndef FFI_H
#define FFI_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int code;
const char* message;
} FfiError;
typedef struct {
double value;
FfiError* error; // NULL if no error
} FfiResult;
FfiResult* safe_divide(int a, int b);
void ffi_result_free(FfiResult* result);
int square(int a);
#ifdef __cplusplus
}
#endif
#endif
In Rust, we must have:
#[repr(C)]
pub struct FfiError {
code: i32,
message: *const c_char, // because in C it's const char*
}
But wait, we are going to allocate a CString and then store its pointer as *const c_char? That's okay because CString::into_raw returns *mut c_char and we can cast it to *const when storing. Then when freeing, we need to cast it back to *mut to pass to CString::from_raw.
So:
let c_message = CString::new(message).unwrap();
let raw = c_message.into_raw(); // *mut c_char
let error = FfiError {
code,
message: raw as *const c_char, // cast to *const
};
Then in ffi_error_free:
let _ = CString::from_raw(error.message as *mut c_char);
This is safe because we know that error.message was originally from a CString::into_raw.
But note: the FfiError struct in Rust has message: *const c_char but in the C header it's const char*. That's the same.
Now, what about the FfiResult? It has error: *mut FfiError because in C it's FfiError* (which is a pointer to a mutable FfiError? Actually, in C it's just a pointer, and we are going to free it so we need to mutate it (to free it). But the C code should not modify the FfiError? Actually, the C code should not modify the FfiError, but when we free we are going to deallocate it. So we need a mutable pointer to free it.
In C, the type is FfiError* which is a pointer to a non-const FfiError? Actually, the C header doesn't have const for the error pointer. So we can have:
In Rust:
#[repr(C)]
pub struct FfiResult {
value: f64,
error: *mut FfiError, // because we will free it, so we need mutable.
}
And in C:
typedef struct {
double value;
FfiError* error; // pointer to FfiError (non-const) because we will free it.
} FfiResult;
Now, let's adjust the create_ffi_error function:
fn create_ffi_error(code: i32, message: &str) -> FfiError {
let c_message = CString::new(message).unwrap();
let raw = c_message.into_raw();
FfiError {
code,
message: raw as *const c_char,
}
}
And the safe_divide:
#[no_mangle]
pub extern "C" fn safe_divide(a: i32, b: i32) -> *mut FfiResult {
if b == 0 {
let error = create_ffi_error(1, "Division by zero");
let result = FfiResult {
value: 0.0,
error: Box::into_raw(Box::new(error)),
};
Box::into_raw(Box::new(result))
} else {
let result = FfiResult {
value: a as f64 / b as f64,
error: std::ptr::null_mut(),
};
Box::into_raw(Box::new(result))
}
}
Then the free functions:
#[no_mangle]
pub extern "C" fn ffi_error_free(error: *mut FfiError) {
if !error.is_null() {
unsafe {
let _ = CString::from_raw(error.message as *mut c_char);
Box::<FfiError>::from_raw(error);
}
}
}
#[no_mangle]
pub extern "C" fn ffi_result_free(result: *mut FfiResult) {
if !result.is_null() {
unsafe {
if !(*result).error.is_null() {
ffi_error_free((*result).error);
}
Box::<FfiResult>::from_raw(result);
}
}
}
Now, we must also consider that the C code might call ffi_result_free on a result that has an error, and then we free the error. This is safe because we set the error pointer to a heap-allocated FfiError in the error case.
But note: the C code must not use the result after freeing it.
Now, let's write tests.
We'll write an integration test that uses the C ABI. We can do this by creating a C test file that links against our Rust library, or we can write Rust tests that call the functions directly (but then we are not testing the ABI). To test the ABI, we need to compile the Rust code as a static or dynamic library and then call it from C.
However, for simplicity, we can write a Rust test that calls the unsafe FFI functions (which are the same as the C ABI) and checks the behavior. But note: this doesn't test the ABI compatibility with C, it just tests that the functions work when called from Rust with the same ABI.
To truly test the ABI, we need a C compiler and a way to link. We can use cbindgen to generate the C header and then write a C test. But for the purpose of this example, we'll write a Rust test that calls the unsafe functions and checks the results, and we assume that the ABI is correct because we are using #[repr(C)] and extern "C".
However, we must also test that the memory is freed correctly (no leaks). We can use #[test] and check for leaks with tools like valgrind or AddressSanitizer. But that's beyond the scope of a simple example.
Let's write a simple test:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_square() {
let result = square(5);
assert_eq!(result, 25);
}
#[test]
fn test_safe_divide_success() {
let result_ptr = safe_divide(10, 2);
let result = unsafe { &*result_ptr };
assert!(result.error.is_null());
assert_eq!(result.value, 5.0);
unsafe { ffi_result_free(result_ptr) };
}
#[test]
fn test_safe_divide_error() {
let result_ptr = safe_divide(10, 0);
let result = unsafe { &*result_ptr };
assert!(!result.error.is_null());
let error = unsafe { &*result.error };
assert_eq!(error.code, 1);
// We can check the error message, but note: it's a C string.
let error_message = unsafe { CString::from_raw(error.message as *mut c_char) };
assert_eq!(error_message.to_str().unwrap(), "Division by zero");
// But note: we just converted the raw pointer to a CString and then dropped it?
// Actually, we are creating a new CString and then dropping it at the end of the block.
// But we must not free the error.message again because we are about to free the entire FfiResult.
// However, in our `ffi_result_free` we will free the error and its message. So we must not free it here.
// So we should not convert it to a CString and then drop it? Because then we are freeing the string twice.
// Instead, we can check the string without taking ownership:
let error_message_cstr = unsafe { CStr::from_ptr(error.message) };
assert_eq!(error_message_cstr.to_str().unwrap(), "Division by zero");
unsafe { ffi_result_free(result_ptr) };
}
}
But note: in the error test, we are using CStr::from_ptr which does not take ownership. That's safe because the ffi_result_free will free the string later.
However, note: the FfiError is freed by ffi_error_free which uses CString::from_raw to free the string. So we must not free the string again.
So the test is okay.
But wait: in the test_safe_divide_error we are using CStr::from_ptr to read the string, and then we free the entire result (which frees the error and the string). That's correct.
Now, we must also test that the ffi_result_free works correctly and doesn't double free.
We can write a test that calls ffi_result_free twice? That would be unsafe and should crash, so we don't want that.
Instead, we can test that after freeing, the pointer is not used again.
But for our example, we trust the implementation.
Now, let's write the C header generation. We can use cbindgen but we are not going to set that up here. Instead, we'll write the C header manually and hope that the Rust structs layout matches.
However, note: the FfiError and FfiResult must be #[repr(C)] which we have.
Now, let's consider the ABIs:
- The functions are
extern "C" so they use the C ABI.
- The structs are
#[repr(C)] so they have the same layout as in C.
But note: the FfiResult has a f64 and a *mut FfiError. On 64-bit, both are 8 bytes, so the struct might be 16 bytes. But there could be padding? Actually, the alignment of f64 is 8, and the alignment of a pointer is 8 (on 64-bit). So the struct will be 16 bytes with no padding.
We can check with std::mem::size_of::<FfiResult>().
Now, let's write a C test (if we want to test the ABI from C). But that's beyond the scope of this example.
Alternatively, we can write a Rust test that uses std::mem::transmute to ensure the sizes and alignments match? But that's not necessary if we use #[repr(C)] and extern "C".
However, to be thorough, we can write:
#[test]
fn test_ffi_result_layout() {
assert_eq!(std::mem::size_of::<FfiResult>(), 16);
assert_eq!(std::mem::align_of::<FfiResult>(), 8);
}
But note: on 32-bit, pointers are 4 bytes and f64 is 8 bytes, so the struct would be 12 bytes? Actually, the alignment of f64 is 8, so the struct might be 16 bytes even on 32-bit? Let's check: the f64 must be aligned to 8, so the struct will have 4 bytes of padding after the pointer? Actually, the order is: f64 (8 bytes) then pointer (4 bytes) -> that would be 12 bytes, but then the struct alignment is the maximum of the two, which is 8. So the struct size must be a multiple of 8. So 12 is not a multiple of 8, so it will be padded to 16.
So on 32-bit, we might have:
offset 0: f64 (8 bytes)
offset 8: pointer (4 bytes) and then 4 bytes padding -> total 16.
So the size is 16 on both 32 and 64 bit? Not necessarily on 64-bit: 8+8=16, no padding. On 32-bit: 8+4+4(padding)=16.
So we can assert size 16.
But note: this is an implementation detail of the ABI. We are relying on the C representation.
Now, what about the FfiError? It has i32 (4 bytes) and *const c_char (4 or 8). On 32-bit: 4+4=8, no padding. On 64-bit: 4+4(padding)+8? Actually, the alignment of a pointer is 8 on 64-bit, so the struct must be padded to 16? Let's see:
code: i32, 4 bytes, alignment 4.
message: *const c_char, 8 bytes, alignment 8.
So the struct will have 4 bytes for code, then 4 bytes of padding, then 8 bytes for message -> total 16.
On 32-bit: i32 (4) and pointer (4) -> 8 bytes.
So we cannot have a fixed size for FfiError. We must not assume the same size on all platforms.
Therefore, we should not test the size of FfiError in a cross-platform way? Actually, the C header must be correct for each platform. But note: we are generating the Rust code and the C header must match.
We can adjust the C header to have the same layout? Actually, the C compiler will pad the structs as needed. So we don't need to worry about the exact size as long as the fields are in the same order and the types are compatible.
But we must ensure that the Rust and C layouts are the same. We can use #[repr(C)] and then in C we rely on the compiler. This is usually safe.
However, to be safe, we can avoid exposing structs that have different sizes on different platforms? But that's not always possible.
Alternatively, we can change the design to avoid platform-dependent structs? We can use:
typedef struct {
int32_t code;
const char* message;
} FfiError;
And in Rust:
#[repr(C)]
pub struct FfiError {
code: i32,
message: *const c_char,
}
Then on 32-bit, the struct is 8 bytes, on 64-bit it's 16? Actually, on 64-bit, the pointer is 8 bytes and the i32 is 4, so the struct will be 16 (with 4 bytes padding after the i32). So the size is different.
But that's okay because the C code will have the same padding. The important thing is that the offset of message is the same. In Rust, the offset of message will be 4 on 32-bit and 8 on 64-bit? Let's check:
On 64-bit:
offset of code: 0
offset of message: 8 (because 4 bytes for code, then 4 bytes padding to align the pointer to 8)
On 32-bit:
offset of code: 0
offset of message: 4 (no padding because the pointer is 4-byte aligned and 4 is divisible by 4)
So the offset of message is different. But in C, the same will happen: the compiler will insert padding to align the pointer.
So as long as we use #[repr(C)] and the same types, the layout will be the same.
But note: we are using i32 for code and *const c_char for message. That matches the C int and const char* (on most platforms, int is 4 bytes). But note: the C standard says int is at least 2 bytes, but on most platforms it's 4. We can use int32_t in C to be sure.
So let's change the C header to:
#include <stdint.h>
typedef struct {
int32_t code;
const char* message;
} FfiError;
And in Rust, we use i32.
Now, we are safe.
But wait: what about the FfiResult? It has double and FfiError*. The double is 8 bytes and has alignment 8. The FfiError* is a pointer (4 or 8 bytes). The alignment of the struct will be 8 because of the double. So:
On 64-bit:
offset of value: 0 (8 bytes)
offset of error: 8 (8 bytes) -> total 16.
On 32-bit:
offset of value: 0 (8 bytes)
offset of error: 8 (4 bytes) -> then 4 bytes padding? Actually, the struct alignment is 8 (because of the double), so the total size must be a multiple of 8. 8+4=12, so we need 4 bytes padding at the end -> total 16.
So the size of FfiResult is 16 on both 32 and 64 bit? Not necessarily: on 32-bit, the pointer is 4 bytes, so we have 8 (double) + 4 (pointer) + 4 (padding) = 16. Yes.
So we can assert that size_of::<FfiResult>() is 16.
But note: the C standard doesn't guarantee that double is 8 bytes, but on most platforms it is. We are assuming IEEE 754 double.
So we are safe for typical platforms.
Now, let's write the tests for the layout:
#[test]
fn test_ffi_result_layout() {
assert_eq!(std::mem::size_of::<FfiResult>(), 16);
assert_eq!(std::mem::align_of::<FfiResult>(), 8);
assert_eq!(std::mem::size_of::<FfiError>(), if cfg!(target_pointer_width = "64") { 16 } else { 8 });
}
But we don't want to condition on the pointer width? Actually, we can just compute the expected size:
For FfiError:
size_of::() + size_of::<*const c_char>() + padding (to align the pointer to its alignment) and then the struct alignment is the max of the two.
But we can just check that the offset of message is correct? Actually, we can check:
#[test]
fn test_ffi_error_layout() {
let expected_message_offset = if cfg!(target_pointer_width = "64") { 8 } else { 4 };
assert_eq!(offset_of!(FfiError, message), expected_message_offset);
}
But offset_of! is not stable in Rust. We can compute it manually:
unsafe fn offset_of<T>(field: &T) -> usize {
let base = 0usize;
let field_ptr = field as *const _ as usize;
field_ptr - base
}
But that's undefined behavior? Actually, we can use ptr::addr_of? Not stable.
Alternatively, we can use the memoffset crate.
But for simplicity, we'll skip the layout tests and rely on #[repr(C)].
However, note: the FfiResult has a double and a pointer. We can compute the offset of the error pointer:
#[test]
fn test_ffi_result_layout() {
let result = FfiResult { value: 0.0, error: std::ptr::null_mut() };
let error_ptr = &result.error as *const *mut FfiError as usize;
let result_ptr = &result as *const FfiResult as usize;
let offset = error_ptr - result_ptr;
// On 64-bit: offset should be 8.
// On 32-bit: offset should be 8 (because the double is 8 bytes, then the pointer at offset 8).
assert_eq!(offset, 8);
}
But note: the value is 8 bytes, so the error should be at offset 8 on both 32 and 64 bit? On 32-bit, the double is 8 bytes, so the next available offset is 8. The pointer is 4 bytes, so it fits at offset 8. Then the struct will have 4 bytes of padding after the pointer to make the struct size 16 (because the alignment of the struct is 8). So the offset of error is 8 on both.
So we can assert that the offset of error is 8.
But note: we are using result_ptr and error_ptr as usize. This is safe because we are just subtracting pointers within the same allocation.
However, this is undefined behavior in safe Rust? Actually, it's safe to cast a reference to a raw pointer and then to usize? And then subtract? That's not allowed in safe Rust because pointer arithmetic is unsafe. So we must do it in an unsafe block.
But we are in a test, so we can do:
#[test]
fn test_ffi_result_layout() {
let result = FfiResult { value: 0.0, error: std::ptr::null_mut() };
let error_addr = unsafe { (&result.error as *const _ as usize) };
let result_addr = unsafe { (&result as *const _ as usize) };
assert_eq!(error_addr - result_addr, 8);
}
But note: the result is a temporary and we are taking its address. That's okay.
However, this is still a bit fragile because we are relying on the layout.
Alternatively, we can use memoffset crate to get the offset safely.
Given the complexity, and since we are using #[repr(C)], we might skip these tests and rely on the fact that the Rust compiler will lay out the structs as specified for the target.
But if we want to be absolutely sure, we can write the C test.
However, for the purpose of this example, we'll assume the layout is correct.
Now, let's write a C test (if we have a C compiler). We'll skip that because it's more involved.
Instead, we'll write a Rust test that uses the FFI functions and checks the behavior, and we'll also check that the memory is freed without leaks.
We can use std::rc::Rc to count allocations? Not really.
We can use #[global_allocator] to track allocations? That's too heavy.
Alternatively, we can run the test with valgrind or ASAN.
But for simplicity, we'll just call the functions and check the results.
Now, let's put it all together.
We'll create a library crate with the above code and tests.
But note: we are exposing FfiError and FfiResult as public, so the C code can use them.
However, we must also provide the C header. We can generate it with cbindgen or write it manually.
Let's write a manual C header (ffi.h) and then in the Rust code we must ensure it matches.
Steps:
- Create
src/lib.rs with the code above.
- Create
include/ffi.h with the C declarations.
- Write tests in
src/tests/ or in src/lib.rs under #[cfg(test)].
But note: we are building a Rust library that will be linked with C. We must set crate-type to staticlib or cdylib in Cargo.toml.
Let's adjust Cargo.toml:
[lib]
name = "my_ffi"
crate-type = ["cdylib"]
Then we can build with cargo build and get a libmy_ffi.so (or .dylib or .dll).
Now, the C code can include ffi.h and link with -lmy_ffi.
But we are not writing C code here, we are writing Rust tests.
So we'll write the tests in Rust that call the unsafe functions.
However, note: the tests must be in the same crate? Yes, because we are testing the private functions? Actually, the functions are public (because we have #[no_mangle] and pub). So we can call them from the tests.
Let's write the tests as above.
But note: the test_safe_divide_error we wrote earlier uses CString::from_raw on the error message? Actually, we changed to use CStr::from_ptr to avoid taking ownership. So let me adjust:
#[test]
fn test_safe_divide_error() {
let result_ptr = safe_divide(10, 0);
let result = unsafe { &*result_ptr };
assert!(!result.error.is_null());
let error = unsafe { &*(result.error) };
assert_eq!(error.code, 1);
let error_message = unsafe { CStr::from_ptr(error.message) };
assert_eq!(error_message.to_str().unwrap(), "Division by zero");
unsafe { ffi_result_free(result_ptr) };
}
This should work.
Now, we must also test that when we free the result, the error and its message are freed.
We can do:
#[test]
fn test_free_result_with_error() {
let result_ptr = safe_divide(10, 0);
unsafe { ffi_result_free(result_ptr) };
// After freeing, we should not use the pointer again.
// But we can check that the pointer is not dangling? We can't really.
}
We can use a tool like valgrind to check for leaks.
Alternatively, we can use the std::alloc::System and count allocations? That's too complex.
We'll leave it at that.
Now, let's write the complete code.
However, note: the safe_divide function returns a *mut FfiResult that is allocated with Box::into_raw. The ffi_result_free uses Box::from_raw to free it. That's correct.
But what about the FfiError inside? We allocate it with Box::into_raw and then free it with Box::from_raw in ffi_error_free. That's correct.
Now, we must also consider that the C code might call ffi_error_free directly? We don't expose that? Actually, we do expose ffi_error_free? In the C header we only have ffi_result_free. We don't expose ffi_error_free because the C code should not free the error directly; it should free the result which in turn frees the error.
But what if the C code wants to extract the error and then free it separately? We don't support that. We designed it so that the entire FfiResult is freed by ffi_result_free.
So we should not expose ffi_error_free in the C header. We only expose ffi_result_free.
But in the Rust code, we have ffi_error_free as a helper for ffi_result_free. We can make it private? Actually, we are using it in ffi_result_free and we are exposing it with #[no_mangle]? We are exposing it because we have #[no_mangle] and pub. We should remove #[no_mangle] and make it private? Then the C code cannot call it.
Let's change:
#[no_mangle]
pub extern "C" fn ffi_error_free(...) // remove this
fn ffi_error_free(...) // make it private
Then the C code cannot call it, and only ffi_result_free is exposed.
But note: the FfiResult has a pointer to FfiError. The C code could try to free that pointer with free (from C) and that would be wrong because we allocated it with Box (which uses the Rust global allocator) and we must deallocate it with Box::from_raw.
So we must not expose ffi_error_free. And we must not let the C code try to free the error pointer.
Therefore, we remove the #[no_mangle] and pub from ffi_error_free.
Now, the C code can only free the entire FfiResult with ffi_result_free.
Let's adjust:
fn ffi_error_free(error: *mut FfiError) {
// same as before
}
#[no_mangle]
pub extern "C" fn ffi_result_free(result: *mut FfiResult) {
// same as before, but call the private ffi_error_free
}
Now, the C header only has ffi_result_free.
But wait: what if the C code wants to get the error out and then not free the entire result? We don't support that. The C code must use the result and then free it.
So the design is:
safe_divide returns a heap-allocated FfiResult.
- The C code must call
ffi_result_free when done.
Now, let's write the complete code.
However, note: the FfiResult and FfiError are exposed in the C header. The C code can read the fields, but must not try to free the error pointer.
We are done.
Let's write the code in one file for simplicity.
But note: we are writing a library, so we'll have src/lib.rs and include/ffi.h.
However, for the example, we can put everything in src/lib.rs and write the tests there.
Let's do:
// src/lib.rs
use std::ffi::{c_char, CString, CStr};
use std::ptr;
#[repr(C)]
pub struct FfiError {
code: i32,
message: *const c_char,
}
#[repr(C)]
pub struct FfiResult {
value: f64,
error: *mut FfiError,
}
fn create_ffi_error(code: i32, message: &str) -> FfiError {
let c_message = CString::new(message).unwrap();
let raw = c_message.into_raw();
FfiError {
code,
message: raw as *const c_char,
}
}
#[no_mangle]
pub extern "C" fn square(a: i32) -> i32 {
a * a
}
#[no_mangle]
pub extern "C" fn safe_divide(a: i32, b: i32) -> *mut FfiResult {
if b == 0 {
let error = create_ffi_error(1, "Division by zero");
let result = FfiResult {
value: 0.0,
error: Box::into_raw(Box::new(error)),
};
Box::into_raw(Box::new(result))
} else {
let result = FfiResult {
value: a as f64 / b as f64,
error: ptr::null_mut(),
};
Box::into_raw(Box::new(result))
}
}
fn ffi_error_free(error: *mut FfiError) {
if !error.is_null() {
unsafe {
let _ = CString::from_raw(error.message as *mut c_char);
Box::<FfiError>::from_raw(error);
}
}
}
#[no_mangle]
pub extern "C" fn ffi_result_free(result: *mut FfiResult) {
if !result.is_null() {
unsafe {
if !(*result).error.is_null() {
ffi_error_free((*result).error);
}
Box::<FfiResult>::from_raw(result);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::CStr;
#[test]
fn test_square() {
assert_eq!(square(5), 25);
assert_eq!(square(-3), 9);
}
#[test]
fn test_safe_divide_success() {
let result_ptr = safe_divide(10, 2);
let result = unsafe { &*result_ptr };
assert!(result.error.is_null());
assert_eq!(result.value, 5.0);
unsafe { ffi_result_free(result_ptr) };
}
#[test]
fn test_safe_divide_error() {
let result_ptr = safe_divide(10, 0);
let result = unsafe { &*result_ptr };
assert!(!result.error.is_null());
let error = unsafe { &*(result.error) };
assert_eq!(error.code, 1);
let error_message = unsafe { CStr::from_ptr(error.message) };
assert_eq!(error_message.to_str().unwrap(), "Division by zero");
unsafe { ffi_result_free(result_ptr) };
}
#[test]
fn test_ffi_result_layout() {
let result = FfiResult { value: 0.0, error: ptr::null_mut() };
let error_addr = unsafe { (&result.error as *const _ as usize) };
let result_addr = unsafe { (&result as *const _ as usize) };
assert_eq!(error_addr - result_addr, 8);
}
}
Now, we must also test that the FfiError layout is correct? We can do a similar test for the offset of message in FfiError.
But note: the offset of message in FfiError is size_of::<i32>() (4) plus padding to align the pointer. On 64-bit, the pointer alignment is 8, so the offset is 8. On 32-bit, the pointer alignment is 4, so the offset is 4.
We can test:
#[test]
fn test_ffi_error_layout() {
let error = FfiError { code: 0, message: ptr::null() };
let message_addr = unsafe { (&error.message as *const _ as usize) };
let error_addr = unsafe { (&error as *const _ as usize) };
let offset = message_addr - error_addr;
if cfg!(target_pointer_width = "64") {
assert_eq!(offset, 8);
} else {
assert_eq!(offset, 4);
}
}
But note: we are using ptr::null() which is a *const c_char and we are casting to usize. This is okay.
However, we are in a test and we are allowed to use unsafe.
Now, we must consider that the FfiError might have padding at the end? But we don't care about the end, only the offset of the second field.
This test will pass on 64-bit and 32-bit? Let's see:
On 64-bit:
code: offset 0, size 4, then 4 bytes padding, then message at offset 8.
So offset = 8.
On 32-bit:
code: offset 0, size 4, then message at offset 4 (no padding because the pointer is 4-byte aligned and 4 is divisible by 4).
So offset = 4.
So the test is correct.
Now, we have:
- Ownership boundaries: We are transferring ownership of the
FfiResult and the internal FfiError and CString to the C code. The C code must call ffi_result_free to free them.
- Error mapping: We map a division by zero to an
FfiError with code 1 and a message.
- ABI tests: We test the layout of the structs and the behavior of the functions.
But note: the ABI tests for layout are done in Rust and assume that the Rust compiler's #[repr(C)] matches the C compiler. This is usually true, but to be 100% safe we should test from C.
However, for the purpose of this example, we are satisfied.
Let me adjust the test_ffi_result_layout to be more robust: we are checking that the error pointer is at offset 8 from the start of the struct. That's correct for both 32 and 64 bit? On 32-bit, the struct is 16 bytes and the error is at offset 8 (because the double is 8 bytes). Yes.
So we are done.
But note: the FfiResult has a value (f64) and then error (pointer). The offset of error is the size of value which is 8 on both 32 and 64 bit. So we can just assert that the offset of error is 8.
So we don't need to condition on the architecture for FfiResult.
Now, we must also consider that the FfiResult might have padding after the value to align the error pointer? On 32-bit, the value is 8 bytes (aligned at 8) and the error is 4 bytes (aligned at 4). Since 8 is divisible by 4, the error can be at offset 8 without padding. So the offset is 8.
So the test for FfiResult is correct for both.
Now, we can run the tests.
But note: the test_ffi_error_layout is architecture dependent. We can conditionally check.
Alternatively, we can compute the expected offset:
let expected_offset = std::mem::size_of::<i32>() + if std::mem::align_of::<*const c_char>() > std::mem::align_of::<i32>() {
std::mem::align_of::<*const c_char>() - std::mem::size_of::<i32>() % std::mem::align_of::<*const c_char>()
} else {
0
};
That's complicated. We'll just condition on the pointer width.
Now, let's write the final code.
However, note: the create_ffi_error function uses CString::new(message).unwrap() which will panic if the message contains a null byte. We should handle that? In a real library, we might want to return an error for that? But we are in an FFI function and we cannot panic. We can replace the null byte? Or we can return a different error.
But for simplicity, we'll leave it as unwrap and assume the message is valid UTF-8 without null bytes.
Now, we must also consider that the safe_divide function might panic? It doesn't panic because we only do division and we check for zero.
But what if the division overflows? Actually, for integers, division by zero is the only panic. We are checking for zero, so it's safe.
Now, we are done.
Let me summarize the key points:
-
Ownership: The Rust side allocates the FfiResult and the FfiError and the error message string. The C side must free the entire FfiResult with ffi_result_free, which recursively frees the error and the message.
-
Error mapping: We use a struct with an error code and a message. The error code is an integer and the message is a string.
-
ABI tests: We test the layout of the structs and the behavior of the functions.
Now, we can write the C header:
// ffi.h
#ifndef FFI_H
#define FFI_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int32_t code;
const char* message;
} FfiError;
typedef struct {
double value;
FfiError* error; // NULL if no error
} FfiResult;
int square(int a);
FfiResult* safe_divide(int a, int b);
void ffi_result_free(FfiResult* result);
#ifdef __cplusplus
}
#endif
#endif
And then the C code can use:
#include "ffi.h"
#include <stdio.h>
int main() {
int squared = square(5);
printf("Square: %d\n", squared);
FfiResult* result = safe_divide(10, 2);
if (result->error == NULL) {
printf("10/2 = %f\n", result->value);
} else {
printf("Error: %s\n", result->error->message);
}
ffi_result_free(result);
result = safe_divide(10, 0);
if (result->error == NULL) {
printf("10/0 = %f\n", result->value);
} else {
printf("Error: %s\n", result->error->message);
}
ffi_result_free(result);
return 0;
}
This C code should work.
We must compile the Rust library and link with the C code.
Now, we have a complete example.
Let me note: the FfiError is allocated only in the error case. In the success case, the error field is NULL.
Also, the ffi_result_free function is safe to call with a NULL pointer.
We are done.
Here's a comprehensive guide to safe Rust FFI covering ownership boundaries, error mapping, and ABI testing:
1. Ownership Boundaries
Key Principles:
- Rust → C: Transfer ownership explicitly using
Box::into_raw() or Vec::into_raw_parts()
- C → Rust: Caller retains ownership; Rust only borrows via
*const/*mut
- Never let Rust free memory allocated in C (unless explicitly agreed)
Pattern Examples:
Rust Creating Objects for C:
#[repr(C)]
pub struct FFIObject {
data: *mut u8,
len: usize,
}
#[no_mangle]
pub extern "C" fn ffi_create_object() -> *mut FFIObject {
let vec = vec![1, 2, 3];
let (ptr, len, cap) = vec.into_raw_parts();
Box::into_raw(Box::new(FFIObject {
data: ptr,
len,
}))
}
#[no_mangle]
pub extern "C" fn ffi_free_object(obj: *mut FFIObject) {
if obj.is_null() { return; }
unsafe {
let obj = Box::from_raw(obj);
let _ = Vec::from_raw_parts(obj.data, obj.len, obj.len); // Reconstruct and drop
}
}
C Passing Objects to Rust:
#[no_mangle]
pub extern "C" fn ffi_process_object(
obj: *const FFIObject, // Borrowed, not owned
callback: Option<extern "C" fn(*const u8, usize)>
) -> bool {
if obj.is_null() { return false; }
let obj = unsafe { &*obj }; // Borrow, don't take ownership
// Process using slice (valid for 'obj' lifetime only)
let slice = unsafe { std::slice::from_raw_parts(obj.data, obj.len) };
// ... process slice ...
true
}
2. Error Mapping Strategy
Two-Phase Error Handling:
#[repr(C)]
pub enum FFIResult<T> {
Ok(T),
Err(FFIError),
}
#[repr(C)]
pub struct FFIError {
code: i32,
message: *const c_char, // C-string, owned by FFIError
}
// Helper for conversion
impl FFIError {
fn new(code: i32, msg: &str) -> Self {
let c_msg = CString::new(msg).unwrap();
FFIError {
code,
message: c_msg.into_raw(),
}
}
}
#[no_mangle]
pub extern "C" fn ffi_maybe_fail(input: i32) -> FFIResult<f64> {
match calculate(input) {
Ok(val) => FFIResult::Ok(val),
Err(e) => FFIResult::Err(FFIError::new(e.code(), e.message())),
}
}
#[no_mangle]
pub extern "C" fn ffi_error_free(err: *mut FFIError) {
if !err.is_null() {
unsafe {
let _ = CString::from_raw(err.message as *mut c_char);
Box::<FFIError>::from_raw(err);
}
}
}
Alternative: Error Code + Out Parameter:
#[no_mangle]
pub extern "C" fn ffi_compute(
input: i32,
out_result: *mut f64, // Optional output
out_error: *mut *mut FFIError // Optional error
) -> i32 { // 0 = success, non-zero = error code
if out_result.is_null() || out_error.is_null() {
return 1; // Invalid parameters
}
match compute(input) {
Ok(val) => {
unsafe { *out_result = val; }
*out_error = std::ptr::null_mut();
0
}
Err(e) => {
let err = Box::new(FFIError::new(e.code(), e.message()));
unsafe { *out_error = Box::into_raw(err); }
e.code()
}
}
}
3. ABI Testing
Comprehensive Test Suite:
#[cfg(test)]
mod ffi_tests {
use super::*;
use std::mem;
#[test]
fn test_ffi_result_layout() {
// Verify struct layout matches C expectations
assert_eq!(mem::size_of::<FFIResult<f64>>(), 16); // f64 + discriminant + padding
assert_eq!(mem::align_of::<FFIResult<f64>>(), 8);
// Check field offsets (if needed)
let result = FFIResult::Ok(3.14);
let ptr = &result as *const _ as usize;
let val_ptr = unsafe { &(result.value) as *const _ as usize };
assert!(val_ptr >= ptr); // Simple check
}
#[test]
fn test_ffi_error_roundtrip() {
let err = FFIError::new(42, "test error");
let err_ptr = Box::into_raw(Box::new(err));
// Simulate C usage
unsafe {
let err_ref = &*err_ptr;
assert_eq!(err_ref.code, 42);
let msg = CStr::from_ptr(err_ref.message).to_str().unwrap();
assert_eq!(msg, "test error");
// Clean up
ffi_error_free(err_ptr);
}
}
#[test]
fn test_null_handling() {
assert!(unsafe { ffi_process_object(std::ptr::null(), None) } == false);
assert!(unsafe { ffi_free_object(std::ptr::null_mut()) }.is_none());
}
}
C ABI Validation Tests:
Create a C test file (tests/ffi_test.c):
#include "your_ffi.h"
#include <assert.h>
#include <stdio.h>
void test_square() {
assert(ffi_square(5) == 25);
assert(ffi_square(-3) == 9);
}
void test_error_handling() {
FFIResult* res = ffi_maybe_fail(-1);
assert(res->error != NULL);
assert(strcmp(res->error->message, "invalid input") == 0);
ffi_result_free(res);
res = ffi_maybe_fail(42);
assert(res->error == NULL);
assert(res->value == 42.0 * 2.0); // whatever calculation
ffi_result_free(res);
}
int main() {
test_square();
test_error_handling();
printf("All FFI tests passed!\n");
return 0;
}
Build Script Integration:
build.rs to verify ABI compatibility:
fn main() {
// Emit bindings for C to include
println!("cargo:rustc-link-lib=static=your_ffi");
// Optional: Check ABI size/alignment during build
println!("cargo:warning=FFIResult size: {}", std::mem::size_of::<FFIResult<f64>>());
}
4. Best Practices Summary
Safety Checklist:
- ✅ Use
#[repr(C)] for all FFI types
- ✅ Mark all FFI functions
extern "C"
- ✅ Document ownership transfer in comments
- ✅ Always check for null pointers in unsafe blocks
- ✅ Provide free functions for every allocation function
- ✅ Use
Option<extern "C" fn(...)> for function pointers
- ✅ Never panic in
extern "C" functions - return errors instead
- ✅ Validate all incoming pointers before dereferencing
Common Pitfalls to Avoid:
// ❌ WRONG: Returning reference to temporary
#[no_mangle]
pub extern "C" fn ffi_bad() -> *const u8 {
let temp = vec![1, 2, 3];
temp.as_ptr() // Dangling pointer!
}
// ✅ CORRECT: Transfer ownership
#[no_mangle]
pub extern "C" fn ffi_good() -> *mut u8 {
let vec = vec![1, 2, 3];
vec.into_raw_parts().0 // Caller must free with ffi_free
}
// ❌ WRONG: Double-free when both Rust and C free
#[no_mangle]
pub extern "C" fn ffi_leak(data: *mut u8) {
unsafe { Vec::from_raw_parts(data, len, cap) }; // Rust frees
// But C also has pointer and might free again!
}
// ✅ CORRECT: Clear ownership contract
// Rust creates → C must call ffi_free
// C creates → Rust borrows only, doesn't free
Tooling:
cbindgen: Auto-generate C headers from Rust
cargo-auditable: Check for unsafe code dependencies
cargo-udeps: Verify unused dependencies
cargo-fuzz: Fuzz test FFI boundaries
valgrind/ AddressSanitizer: Detect memory errors
Example: Complete Safe Pattern
//! # Safe FFI Pattern
//!
//! 1. Rust allocates → C frees
//! 2. C allocates → Rust borrows
//! 3. Errors as discriminated unions
//! 4. All unsafe blocks minimized and validated
#[repr(C)]
pub structBuffer {
ptr: *mut u8,
len: usize,
}
#[no_mangle]
pub extern "C" fn buffer_create(size: usize) -> *mut Buffer {
let vec = vec![0u8; size];
let (ptr, len, _) = vec.into_raw_parts();
Box::into_raw(Box::new(Buffer { ptr, len }))
}
#[no_mangle]
pub extern "C" fn buffer_read(
buf: *const Buffer,
offset: usize,
out: *mut u8,
out_len: usize
) -> i32 {
// Validation
if buf.is_null() || out.is_null() { return 1; }
let buf = unsafe { &*buf };
if offset >= buf.len { return 2; }
let available = buf.len - offset;
if out_len > available { return 3; }
// Safe copy (no lifetime issues - we copy)
unsafe {
std::ptr::copy_nonoverlapping(
buf.ptr.add(offset),
out,
out_len
);
}
0 // Success
}
#[no_mangle]
pub extern "C" fn buffer_free(buf: *mut Buffer) {
if !buf.is_null() {
unsafe {
let buf = Box::from_raw(buf);
let _ = Vec::from_raw_parts(buf.ptr, buf.len, buf.len);
}
}
}
Key Takeaways:
- Ownership must be explicit and documented - who allocates, who frees
- Errors should be machine-readable (codes) with optional human messages
- Test ABI compatibility with both Rust and C tests
- Minimize
unsafe blocks and validate everything inside them
- Consider using
libffi or abi_stable crate for complex cases
This approach ensures Rust's safety guarantees extend across the FFI boundary while maintaining C compatibility.