Sub topic 10
Turning C error codes into Result
This chapter assumes you can write Rust Result code, know what unsafe means, and have read the earlier chapters on extern blocks, CStr, and safe wrappers. The goal is to hide C's error conventions behind a Rust API. A caller of your wrapper should never inspect an integer to learn whether a call worked.
How C reports errors
C has no Result, no exceptions, and no shared convention. Libraries pick one of a handful of patterns, and you have to read the documentation to find out which one a given function uses.
| Pattern | Example signature | Success signal | Failure detail |
|---|---|---|---|
| Status code | `int parse_config(const char *, int *)` | return value is 0 | the nonzero value itself |
| Null on failure | `counter *counter_new(void)` | non-null pointer | none, or `errno` |
| Sentinel value | `int close(int)`, `-1` on failure | any other value | `errno` |
| Out-parameter | `int *out` argument | status code says so | filled only on success |
| Last-error function | `const char *lib_last_error(void)` | return value | a separate query call |
The wrapper's job is the same in every case. Check the signal right after the call, build a Rust error value, and return Err. Hand out any data produced by the call only on success.
Status codes and out-parameters
The simplest case is a function that returns a status and writes its real result through a pointer. This is the example from the chapter plan:
use std::ffi::{c_char, c_int, CStr};
// Assumed C API: int parse_config(const char *path, int *out); returns 0 on success, nonzero on failure.
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 out: c_int = 0;
let rc = unsafe { parse_config(path.as_ptr(), &mut out) };
if rc == 0 { Ok(out) } else { Err(rc) }
}Three details matter here.
outis initialized to 0 before the call. Passing a pointer to uninitialized memory as*mut c_intis acceptable only if you never read it before C writes it. Initializing it is simpler. For larger types, useMaybeUninitand callassume_initonly on the success path.- The
Okvalue is read only whenrc == 0. Many C functions leave out-parameters unspecified on failure. Treat them as garbage unless the documentation says otherwise. &mut outcoerces to*mut c_intbecause it is a valid, exclusive reference for the duration of the call. C must not keep the pointer after returning.
A typed error instead of a bare integer
Result<c_int, c_int> forces every caller to know the library's numeric codes. Replace the integer with an enum, and keep an Unknown variant, because C libraries add new codes over time and you don't want a panic or undefined behavior when one appears.
use std::ffi::{c_char, c_int, CStr};
use std::fmt;
// Assumed C API: returns 0 on success, 1 if the file is missing, 2 if it is malformed.
unsafe extern "C" {
fn parse_config(path: *const c_char, out: *mut c_int) -> c_int;
}
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigError {
NotFound,
Malformed,
Unknown(c_int),
}
impl ConfigError {
fn from_code(code: c_int) -> ConfigError {
match code {
1 => ConfigError::NotFound,
2 => ConfigError::Malformed,
other => ConfigError::Unknown(other),
}
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::NotFound => write!(f, "config file not found"),
ConfigError::Malformed => write!(f, "config file is malformed"),
ConfigError::Unknown(code) => write!(f, "unknown config error (code {code})"),
}
}
}
impl std::error::Error for ConfigError {}
pub fn parse(path: &CStr) -> Result<c_int, ConfigError> {
let mut out: c_int = 0;
let rc = unsafe { parse_config(path.as_ptr(), &mut out) };
match rc {
0 => Ok(out),
code => Err(ConfigError::from_code(code)),
}
}Implementing std::error::Error lets callers use ? with Box<dyn Error> and anyhow. Do not use #[repr(C)] enums received from C as Rust enums. If C hands you an integer that matches no variant, creating that enum value is undefined behavior. Receive the integer, then convert it with a match as above.
errno
Many POSIX-style functions return -1 or a null pointer and put the reason in errno, a thread-local integer. Rust wraps this in std::io::Error::last_os_error(). It builds an io::Error from the current OS error number, with a readable message and an ErrorKind you can match on.
This example calls the C library's fopen and fclose. It assumes a Unix-like platform, where errno is what last_os_error reads.
use std::ffi::{c_char, c_int, c_void, CStr};
use std::io;
use std::ptr::NonNull;
unsafe extern "C" {
fn fopen(path: *const c_char, mode: *const c_char) -> *mut c_void;
fn fclose(file: *mut c_void) -> c_int;
}
pub struct CFile {
raw: NonNull<c_void>,
}
impl CFile {
pub fn open_read(path: &CStr) -> io::Result<CFile> {
let raw = unsafe { fopen(path.as_ptr(), c"r".as_ptr()) };
match NonNull::new(raw) {
Some(raw) => Ok(CFile { raw }),
None => Err(io::Error::last_os_error()),
}
}
}
impl Drop for CFile {
fn drop(&mut self) {
unsafe { fclose(self.raw.as_ptr()) };
}
}
fn main() {
let path = c"/definitely/not/here.txt";
match CFile::open_read(path) {
Ok(_) => println!("opened"),
Err(e) => println!("{:?}: {e}", e.kind()),
}
}On Linux this prints NotFound: No such file or directory (os error 2). The c"..." literals need Rust 1.77 or later. Dropping the CFile calls fclose exactly once, which ties this chapter to the RAII wrapper pattern from the previous one.
errno rules
- Read
errnoimmediately. Any other call that toucheserrnocan overwrite it, and Rust code between the C call andlast_os_error()can do that (for example, an allocation that fails and retries). Putlast_os_error()on the line right after the check. - Read it only on failure. A successful call is allowed to change
errnoto a nonzero value, so a nonzeroerrnoafter success means nothing. - Some functions, such as
strtol, can return a value that is also a legitimate result. The C documentation tells you to seterrnoto 0 before the call and check it afterward. Rust's standard library has no portable way to clearerrno. Thelibccrate or a small C helper compiled withcccan do it. If you need this pattern, a short C shim is often the cleanest option. - On Windows,
last_os_error()readsGetLastError, not the C runtime'serrno. C library functions that seterrnoneed platform-specific handling there.
Null pointers and sentinels
A constructor that returns a null pointer on failure maps naturally to Option or Result. The Counter::new() wrapper from the ownership chapter returns Option<Counter> because the C API gives no further detail. If the library documents errno for that failure, return io::Result like CFile::open_read above. If it offers a "last error" function, call it in the failure branch, convert its string with CStr::to_string_lossy, and store it in your error type. Copy the text, since the library may free or overwrite that buffer on its next call.
For sentinel returns, write one small helper so the check lives in a single place:
use std::ffi::c_int;
use std::io;
fn check(rc: c_int) -> io::Result<c_int> {
if rc == -1 {
Err(io::Error::last_os_error())
} else {
Ok(rc)
}
}
fn main() {
println!("{:?}", check(7).ok());
}Call it as check(unsafe { some_c_fn(args) })? and every wrapper function stays short and consistent.
Mapping errors across a wider API
When a library has many functions with the same status-code scheme, define one error type for the whole library and one from_code conversion. Keep these conventions:
- Make the success value the
Okpayload. Callers should never see a status integer on the success path. - Keep the raw code inside the error (an
Unknown(c_int)variant or acode()method) so it can be logged and reported upstream. - Mark the error enum
#[non_exhaustive]if the crate is public. New C codes then become a minor version change instead of a breaking one. - Never
unwrap()a conversion from a C code. The C side can return values you did not expect.
Common mistakes
- Ignoring a return value. C functions that return a status are easy to call as a statement. Rust warns about unused
Resultbut not about an unusedc_int, so wrap every fallible call and use?. - Using the output after failure. If
parse_configfails,outmay hold your initial 0 or something else. Return it only insideOk. - Confusing "no error" codes. Some APIs return 0 for failure and nonzero for success (the Windows
BOOLstyle). Check the documentation for each function rather than assuming zero means success. - Swallowing the detail. Converting every failure to
Noneor a unit error discards information that callers and logs need. - Letting a panic cross into C when reporting errors from a callback. That is covered in the chapter on panics.
Exercise
A C function int read_value(int id, int *out) returns 0 on success, -2 when id is unknown, and -5 when the device is busy, and leaves *out untouched on failure. Write the signature of a safe wrapper and describe how it maps the codes. What should it do for a code such as -9?
Show answer
Use pub fn read_value(id: i32) -> Result<i32, ReadError>, where ReadError has variants UnknownId, Busy, and Unknown(c_int). The wrapper declares let mut out: c_int = 0;, calls read_value(id, &mut out) in an unsafe block, and matches the return value: 0 gives Ok(out), -2 gives Err(ReadError::UnknownId), -5 gives Err(ReadError::Busy), and any other value, including -9, gives Err(ReadError::Unknown(code)). The Unknown variant keeps the wrapper from panicking or misreporting when the library adds a new code. The out-parameter is returned only on the success path.
Exercise
Why is it a bug to write let rc = unsafe { c_call() }; log::debug!("rc = {rc}"); if rc == -1 { return Err(io::Error::last_os_error()); }?
Show answer
The logging call runs between the C call and the errno read. It may allocate, write to a file, or make system calls that change errno, so last_os_error() can report an error from the logging code instead of from c_call. Check the return value and read errno immediately, then log afterward.