Sub topic 10
Turning C error codes into Result
This chapter assumes you can declare extern functions, call them in unsafe blocks, and use CStr for strings. It also assumes you know Rust's Result and ? operator. Here you will convert C's error conventions into idiomatic Rust errors, so callers of your safe wrapper never see raw status codes.
How C reports errors
C has no Result. Libraries signal failure in a few common ways:
| Convention | Example | How to detect failure |
|---|---|---|
| Status code return value | `int parse_config(...)` | Return value is nonzero |
| Sentinel return value | `malloc`, `fopen` | Return value is `NULL` or `-1` |
| `errno` side channel | `open`, `read` | Return value is `-1`, then read `errno` for the reason |
| Out-parameter for the result | `int *out` | Result is only valid when the status is success |
Your wrapper has one job here: check the signal immediately after the call, then return either Ok with the value or Err with a typed error.
Status code plus out-parameter
The most common shape is a status code with the real result written through a pointer. This is the example from the spine:
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:
outis initialized to0before the call. Passing a pointer to uninitialized memory through a plainc_intwould be undefined behavior if C never wrote to it. Initializing avoids the question.- The value in
outis only returned onrc == 0. On failure, C may leave it untouched or write garbage. - The error type is a bare
c_int. That works, but callers cannot tell what it means. The next section fixes that.
Use a real error type
A raw integer in Err pushes the work onto every caller. Define an error type that names the failure and implements the standard traits so ? works.
use std::ffi::{c_char, c_int, CStr};
use std::fmt;
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,
Other(c_int),
}
impl ConfigError {
fn from_code(code: c_int) -> ConfigError {
match code {
1 => ConfigError::NotFound,
2 => ConfigError::Malformed,
other => ConfigError::Other(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::Other(code) => write!(f, "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) };
if rc == 0 {
Ok(out)
} else {
Err(ConfigError::from_code(rc))
}
}The Other variant is deliberate. C libraries add codes over time, and a match with no fallback would either fail to compile or hide new codes. Keeping the original number preserves information for logs and bug reports. The meaning of codes 1 and 2 here is made up for illustration. Take the real values from the library's header or documentation.
Reading errno
Many system-style C functions return -1 and set errno. Rust exposes this through std::io::Error::last_os_error(), which reads errno on Unix and GetLastError on Windows.
use std::ffi::{c_char, c_int, CString};
use std::io;
unsafe extern "C" {
fn open(path: *const c_char, flags: c_int, ...) -> c_int;
fn close(fd: c_int) -> c_int;
}
const O_RDONLY: c_int = 0;
pub fn open_readonly(path: &str) -> io::Result<c_int> {
let c_path = CString::new(path)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
let fd = unsafe { open(c_path.as_ptr(), O_RDONLY) };
if fd == -1 {
Err(io::Error::last_os_error())
} else {
Ok(fd)
}
}
pub fn close_fd(fd: c_int) -> io::Result<()> {
if unsafe { close(fd) } == -1 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}This sketch assumes a Unix platform where O_RDONLY is 0. For portable code, take constants from the libc crate.
Two rules keep errno reliable:
- Read it immediately after the failing call. Any other C function, including ones Rust's standard library calls for you, may overwrite it. Do not allocate, print, or log between the call and
last_os_error(). - Read it only on failure. C functions are allowed to change
errnoeven when they succeed, so a nonzero value after a successful call means nothing.
io::Error also gives you raw_os_error() for the numeric code and a readable Display message from the operating system.
Sentinel pointers
When a function returns a pointer, NULL is the usual failure value. The Counter::new wrapper from the ownership chapter already does this by returning Option<Counter> through NonNull::new. If the library also sets an error code, return a Result instead and fill in the error from that source.
The flow below shows the decision your wrapper makes after every call.
Common mistakes
- Returning the out-parameter on failure. The value may be unset or invalid. Gate it on the success check.
- Reading
errnolate. A drop, an allocation, or a formatting call can reset it. Capture it first. - Assuming
0means success everywhere. Some APIs return a positive count on success and a negative number on failure. Check the library's documentation. - Dropping unknown codes. Always keep a fallback variant.
- Forgetting cleanup on the error path. If C allocated something before failing, check whether you must free it. A RAII wrapper makes this automatic.
Exercise
A C function int read_value(int *out) returns 0 on success and -1 on failure, setting errno. Write the safe wrapper signature and body returning std::io::Result<c_int>. Why must last_os_error() be called before any other work on the failure path?
Show answer
unsafe extern "C" { fn readvalue(out: *mut cint) -> cint; } pub fn read() -> std::io::Result<cint> { let mut out: cint = 0; let rc = unsafe { readvalue(&mut out) }; if rc == 0 { Ok(out) } else { Err(std::io::Error::lastoserror()) } } Other calls, including allocation or formatting, can overwrite errno, so the original failure reason would be lost.