
Recall first from bindgen and cbindgen
- bindgen parses C headers with libclang and emits Rust declarations
- cbindgen reads Rust crate source and emits C declarations for its exported interface
- A generated declaration still needs a compiled implementation at link time
Transfer a Rust allocation to C
4 min readYou generated bindings with bindgen and cbindgen. This lesson answers how ownership transfers across FFI and how to wrap a C library safely.
A Linux program can open a configuration file with glibc's fopen and get back a FILE *. The caller must eventually call fclose. That function closes the stream and releases resources associated with it. A pointer to a Rust allocation can also cross the same boundary, but its release operation comes from the Rust API that created it. Both pointers can be stored in a C variable. The type and address alone do not tell C which cleanup operation the caller owes. fopen(3) and fclose(3)
an API agreement that gives the receiver responsibility for releasing a resource or transferring that responsibility again starts with a specific success condition. For a Rust constructor that always returns an owned pointer when it returns normally, the transfer takes effect on return. For an API that accepts a pointer and may decline it, the contract must specify who owns it after each outcome. If the receiver takes ownership only on success, the original owner must release it on failure. If the receiver consumes it regardless of the result, the original owner must leave it alone after the call.
Box::into_raw consumes a Box<T> and returns a *mut T. The value stays where it was, and the allocation stays live. There is no longer a Box that Rust will drop automatically. The code that takes responsibility can later give the original pointer back to Rust. Box::from_raw reconstructs the owning Box<T>, and dropping that box drops T and releases the allocation through Rust's box allocator.
Consider a small Rust API that exports an opaque context. C can declare an incomplete struct Context and use pointers to it in the function declarations. The field is private to Rust, so the context layout never has to be shared with C. Exported symbols in this example use Rust 2024 syntax.
pub struct Context {
_label: String,
}
#[unsafe(no_mangle)]
pub extern "C" fn context_new() -> *mut Context {
Box::into_raw(Box::new(Context {
_label: String::from("sensor"),
}))
}
/// # Safety
/// `ptr` must be null or a live pointer returned by `context_new`.
/// For a non-null pointer, the caller must own its release obligation.
/// All access through this pointer and its aliases must end before release.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn context_destroy(ptr: *mut Context) {
if !ptr.is_null() {
// SAFETY: The caller transfers the original live allocation back.
drop(unsafe { Box::from_raw(ptr) });
}
}
A C caller keeps the returned pointer until it has finished with the context. It calls context_destroy once and discards every copy. Copying the pointer copies the address. The obligation to release the resource still belongs to one owner. The null check makes context_destroy(NULL) an explicit no-op. An already released pointer may still be non-null, so the check cannot identify a second release. Reconstructing a box also requires the right pointer type and the original allocation position. A pointer to an interior field cannot recover the box.
Use free for a pointer returned by malloc, or for another allocation whose API explicitly specifies free. For a library handle, use the cleanup operation named by the library. For this Box, use context_destroy. Even on a system where Rust's selected allocator calls into the same native heap, a direct C free would skip the Context destructor and the cleanup of its String. Allocator identity can also change with the build. In the other direction, a pointer obtained from malloc carries no assurance that it meets Box::from_raw's allocator, layout, and initialized-value requirements. Keep the release function in the API that defines those requirements. malloc(3)
Choose FFI types for the data being passed
3 min readstd::ffi contains types for several distinct jobs. Use CString when Rust owns a byte string that C expects to be NUL-terminated. CString::new rejects an interior zero byte and adds the terminator. as_ptr() lets C borrow the bytes while the CString stays alive. Keep the owning variable in scope until the call returns, and use this approach only if the C API promises to finish using the bytes within that lifetime. An API that retains the pointer requires storage that stays alive until the library releases the borrow.
CStr represents a borrowed C string and usually appears as &CStr in a Rust API. When C returns a pointer to a library-owned string, use CStr::from_ptr only after establishing the library's guarantees. The pointer must refer to readable bytes through the terminating NUL in one allocation, and the bytes must stay alive and unmodified for the borrow. For a string tied to a handle, a method returning &CStr can tie the borrow to &self if the API guarantees that the bytes remain stable throughout that borrow. If the next C call can overwrite the bytes, an owned copy before that call gives the Rust caller independent storage. Convert to &str with to_str() only when you can handle invalid UTF-8.
CString also has an ownership API. A pointer produced by CString::into_raw is returned to Rust with CString::from_raw, exactly once. This pair has an extra requirement because reclamation recomputes the string length. C may use the original string, but it must preserve the position of the first NUL byte. If the library expects a string it can change in length or release with free, choose the allocation interface documented by that library.
OsStr and OsString represent borrowed and owned operating-system strings. They are useful in the public Rust API, where Path::as_os_str() gives you a borrowed OsStr. On embedded Linux, path components can contain bytes that are invalid UTF-8. Use the Unix OsStrExt::as_bytes() method and pass the bytes directly to CString::new. A zero byte anywhere in the path must fail conversion because passing it to a C path API would terminate the path early. Forcing the path through a lossy Unicode conversion can change which file the program opens.
For raw declarations, use the c_* types that correspond to the C header. c_char matches C's plain char, whose signedness depends on the target. c_int matches int, c_long matches long, and c_void is used behind pointers for void *. Choosing c_long for a C long preserves the declaration across Linux targets with different widths for that type. VaList represents a C va_list for variadic argument access or forwarding. It depends on the target ABI, and Rust's VaList API requires nightly. For a stable wrapper around a variadic interface, a fixed-signature C helper can perform the variadic call with the intended argument types.
Build a safe wrapper around a C stream
5 min readUse fopen, fgetc, ferror, and fclose from glibc to build a read-only stream. These functions are available in the normal Ubuntu Rust target's C runtime link. The wrapper needs four facts from the C API. Opening in read mode returns either a valid stream or a null pointer. A successful open gives the caller responsibility for closing the stream. A read returns the byte as an unsigned char converted to int, or EOF on end of file or error. After fclose returns, further access to the stream is invalid, including after a reported close failure. fopen(3), fgetc(3), and fclose(3)
use std::ffi::{c_char, c_int, CString};
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
use std::ptr::NonNull;
mod raw {
use super::{c_char, c_int};
#[repr(C)]
pub struct File {
_opaque: [u8; 0],
}
unsafe extern "C" {
pub fn fopen(path: *const c_char, mode: *const c_char) -> *mut File;
pub fn fgetc(stream: *mut File) -> c_int;
pub fn ferror(stream: *mut File) -> c_int;
pub fn fclose(stream: *mut File) -> c_int;
}
}
pub struct InputStream {
stream: NonNull<raw::File>,
}
impl InputStream {
pub fn open(path: &Path) -> io::Result<Self> {
let path = CString::new(path.as_os_str().as_bytes())
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
// SAFETY: Both pointers name live NUL-terminated strings for this call.
let stream = unsafe { raw::fopen(path.as_ptr(), c"r".as_ptr()) };
let stream = NonNull::new(stream).ok_or_else(io::Error::last_os_error)?;
Ok(Self { stream })
}
pub fn read_byte(&mut self) -> io::Result<Option<u8>> {
// SAFETY: This wrapper owns a live stream and has exclusive access.
let value = unsafe { raw::fgetc(self.stream.as_ptr()) };
if value >= 0 {
return Ok(Some(value as u8));
}
// Save errno from the read before another C call.
let read_error = io::Error::last_os_error();
// SAFETY: fgetc leaves the stream live, even on EOF or error.
if unsafe { raw::ferror(self.stream.as_ptr()) } != 0 {
Err(read_error)
} else {
Ok(None)
}
}
}
impl Drop for InputStream {
fn drop(&mut self) {
// SAFETY: A successful open transfers one live stream to this owner.
let _ = unsafe { raw::fclose(self.stream.as_ptr()) };
}
}
The opaque File declaration gives the binding a typed pointer. The wrapper never constructs or dereferences a File value. The private NonNull field is set only after successful construction, and the wrapper exposes no constructor from a raw pointer. Together those choices establish the invariant used in every unsafe block. NonNull alone only excludes null. The wrapper's API is what ensures that all successfully constructed values own live streams. Moving an InputStream moves its cleanup obligation. The wrapper leaves the thread-sharing traits at their defaults.
read_byte takes &mut self because reading advances the stream and can update its indicators. On this Linux interface, valid bytes produce nonnegative values, so check the signed result before narrowing it to u8. A byte with all bits set is valid input. A negative result requires checking ferror, which returns nonzero when the error indicator is set. The wrapper reads the OS error immediately after the negative result and uses it only on the error branch. The error indicator persists, so the caller should stop reading after an error. This small API offers no operation to clear that indicator. ferror(3)
Here, Drop performs best-effort cleanup for a read-only stream and discards the close status. If an API needs to report close failures, add a consuming close operation and take the handle out of an Option before calling fclose. Drop can then close only when that option still holds a handle. Removing the handle before the call ensures that a reported failure cannot trigger an invalid second close.
Going deeperExplore the mechanism
Undefined behavior at the boundary. A null dereference can occur when code treats a failed fopen as a valid stream. A dangling dereference can occur when code uses a pointer after its owner closes or frees it. In an executed Rust model, Miri can diagnose a memory access through null or through a pointer to a freed allocation. Merely holding either raw pointer does not exercise the invalid access.
A wrong function signature can cause the caller and callee to disagree on how to pass or interpret arguments and results. Compare the binding to the actual C declaration, including the ABI. Miri can flag incompatible indirect calls when it can see both the interpreted call and the actual interpreted function. A declaration for an arbitrary native C symbol provides Miri no C implementation to compare against.
An output pointer can refer to allocated storage that still contains uninitialized bytes. With a C API that promises to write a scalar only on success, pass writable MaybeUninit<T> storage and call assume_init only on the status that guarantees a complete write. In a Rust model where the callee skips the write, Miri can diagnose treating the uninitialized scalar as a value. Miri checks executed operations in interpreted Rust and supported shims. Model native calls to check the Rust assumptions, and verify the native library's actual contract separately.
In Unit, integration, and doc tests, you will choose where to check ordinary reads, end of file, and rejected paths so callers can rely on the behavior this wrapper exposes.
Key takeaways
- Box::into_raw consumes the Box and leaves its allocation live until the agreed owner releases it.
- An FFI pointer needs an explicit lifetime, ownership rule, and matching release function.
- A safe wrapper establishes C preconditions internally and represents failures with Rust types.
- Miri can diagnose exercised violations in modeled Rust code, while native C code requires separate verification.
Reflect
- Explain to a colleague, in two sentences: trace ownership from Box::into_raw to exactly one Box::from_raw.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagemalloc(3): allocation and release
- Man pagefopen(3): open a stream
- Man pagefgetc(3): read a byte from a stream
- Man pagefclose(3): close a stream
- ReferenceBox::into_raw and Box::from_raw (Rust std docs)
Official documentation first. Links checked when the lesson was published.