Sub topic 3
Matching C types in Rust
This chapter covers how C's primitive types and pointers map to Rust types in an extern declaration. It assumes you know basic Rust (ownership, borrowing, Result), can read a Cargo project, understand C pointers and malloc/free, and know what unsafe means. Earlier chapters showed how to declare and call a C function. Here you learn how to write the signature so that it matches what the C compiler produced.
Why the signature must match exactly
When Rust calls a C function, the compiler trusts your declaration. It does not read the C header. If your declaration says a parameter is a 32-bit integer and the C function expects a 64-bit one, the program still compiles and links. It then passes the wrong number of bytes in the wrong register or stack slot. The result is undefined behavior, which usually shows up as garbage values or crashes far from the cause.
So the job in this chapter is a translation task. For each C type in a function signature, you pick a Rust type with the same size, alignment, and calling convention.
The problem with `int` and `long`
C does not fix the size of its basic types. int is at least 16 bits and is usually 32. long is 64 bits on 64-bit Linux and macOS, but 32 bits on 64-bit Windows. char may be signed or unsigned depending on the platform.
Rust's i32 and i64 have fixed sizes. If you write i64 for a C long, your code works on Linux and silently breaks on Windows. The fix is to use the C-named aliases from std::ffi, which the compiler resolves to the right Rust type for the target platform.
The `std::ffi` type aliases
The standard library provides these aliases. Older code may use std::os::raw or the libc crate for the same names. The std::ffi versions are the current standard path.
| C type | Rust alias | Typical size |
|---|---|---|
| `char` | `c_char` | 8 bits (signedness varies by platform) |
| `signed char` | `c_schar` | 8 bits |
| `unsigned char` | `c_uchar` | 8 bits |
| `short` | `c_short` | 16 bits |
| `unsigned short` | `c_ushort` | 16 bits |
| `int` | `c_int` | 32 bits |
| `unsigned int` | `c_uint` | 32 bits |
| `long` | `c_long` | 32 or 64 bits |
| `unsigned long` | `c_ulong` | 32 or 64 bits |
| `long long` | `c_longlong` | 64 bits |
| `unsigned long long` | `c_ulonglong` | 64 bits |
| `float` | `c_float` | 32 bits (`f32`) |
| `double` | `c_double` | 64 bits (`f64`) |
| `void` (in a pointer) | `c_void` | not a value type |
c_float and c_double are just other names for f32 and f64, so you can use either. The integer aliases are different. Prefer them over i32 or i64 even where they happen to be equal on your machine, because that documents intent and keeps the code portable.
The example from the topic plan uses these aliases:
use std::ffi::{c_char, c_int, CString};
unsafe extern "C" {
fn abs(input: c_int) -> c_int;
fn strlen(s: *const c_char) -> usize;
}
fn main() {
let n = unsafe { abs(-3) };
let s = CString::new("hello").unwrap();
let len = unsafe { strlen(s.as_ptr()) };
println!("{n} {len}");
}This prints 3 5. abs takes and returns a C int, so c_int is correct. strlen returns size_t, which is covered next.
Types with a fixed-size or special mapping
Some C types have a closer Rust match than the generic aliases.
size_tandssize_t.size_tis an unsigned integer big enough to hold any object size. On mainstream platforms it has the same width as a pointer, so Rust'susizematches it. Likewisessize_tmatchesisize. The code above usesusizefor the result ofstrlenfor this reason. On unusual platforms where the widths differ, thelibccrate'ssize_tis the safer choice.- Fixed-width types. C's
int32_t,uint8_t,int64_t, and the rest from<stdint.h>map directly toi32,u8,i64, and so on. When a header uses these, use the Rust primitives. bool. C99's_Bool(boolin<stdbool.h>) maps to Rust'sbool. Both are one byte, and both only allow the values 0 and 1. If a C function returns some other nonzero value through abool-typed field, that is already undefined behavior in C. Many older APIs useintfor flags. In that case declarec_intand compare it to zero yourself.voidreturn. A C function that returnsvoidis declared in Rust with no return type.void *. This becomes*mut c_voidor*const c_void. It is an untyped address, and you cast it to a real type on the Rust side.
A Rust char is not a C char. Rust's char is a 32-bit Unicode scalar value. A C char is a single byte. Never use Rust char in an extern signature to mean a C char.
Raw pointers
C pointers become Rust raw pointers. There are two forms.
*const Tis a pointer you promise not to write through. It matches C'sconst T *.*mut Tis a pointer that may be written through. It matchesT *.
Rust does not enforce const-ness on raw pointers the way it enforces borrows on references. Matching const still matters. It records the C API's contract, and it lets you pass a &T without taking a mutable borrow.
Raw pointers have no lifetime and no ownership. They may be null, dangling, or misaligned, and the compiler does not check any of that. Creating a raw pointer is safe. Dereferencing one is unsafe.
Pointer-to-pointer and out-parameters
A C function that fills in a value for the caller usually takes a pointer to that value. A C int *out becomes *mut c_int. To call it, declare a local variable, then pass its address:
use std::ffi::{c_char, c_int};
unsafe extern "C" {
fn parse_config(path: *const c_char, out: *mut c_int) -> c_int;
}
pub fn parse_into(path: *const c_char) -> Option<c_int> {
let mut out: c_int = 0;
let rc = unsafe { parse_config(path, &mut out) };
if rc == 0 { Some(out) } else { None }
}Here &mut out is a &mut c_int, and Rust coerces it to *mut c_int at the call. The function is hypothetical. It stands in for any C API that returns a status code and writes a result through a pointer. A later chapter develops the error-handling side.
References versus raw pointers in signatures
You can write &T or &mut T directly in an extern declaration. Both have the same representation as a non-null pointer to T. The third code example in the plan does this indirectly: it declares *const Point and passes &Point values to it, relying on the coercion from reference to raw pointer.
Using raw pointers in the declaration is the safer default. A reference in a signature tells the compiler that the pointer is non-null, aligned, and valid for the whole call, and the optimizer will act on that. If the C side can ever hand back or accept null, a reference is wrong and the program has undefined behavior. For values that may be null, use *const T, or Option<&T> where you want the null case to be an explicit None.
Nullable pointers and `Option`
Rust guarantees a special layout rule, called the niche optimization, for a few types. Option<&T>, Option<&mut T>, Option<NonNull<T>>, and Option<extern "C" fn(...)> all have the same size and representation as a single pointer, with None stored as null. That makes them valid in an FFI signature, and the compiler checks the null case for you.
use std::ffi::c_int;
#[repr(C)]
pub struct Config {
pub verbose: c_int,
}
unsafe extern "C" {
// C side: int run(const config *cfg); cfg may be NULL for defaults
fn run(cfg: Option<&Config>) -> c_int;
}
pub fn run_default() -> c_int {
unsafe { run(None) }
}
pub fn run_with(cfg: &Config) -> c_int {
unsafe { run(Some(cfg)) }
}This only works for the types listed. Option<Box<T>> also has the null layout, but passing a Box transfers ownership to C, so that belongs in the chapter on ownership. Option<*const T> does not get the niche. It is larger than a pointer and must not appear in a signature.
Function pointers
A C function pointer such as void (*cb)(int) maps to extern "C" fn(c_int). The extern "C" part is required. A plain Rust fn(c_int) uses the Rust calling convention, which is not stable and may differ from C's. Mixing them is undefined behavior. Callbacks are covered in detail in a later chapter.
What not to use
Some Rust types look convenient but have no defined C layout. Do not put these in an extern signature or in a struct shared with C.
String,&str, and&[T]. Their layout is not specified, and&strand slices are two words wide (pointer and length), which C does not expect. Use a pointer and a length as separate arguments, or useCString/CStras the next chapter explains.Vec<T>andBox<dyn Trait>. Same problem.- Plain Rust
enumwith fields, and tuples. Their layouts are unspecified. u128andi128. Their alignment on some platforms differs from the matching C type, and the rules have changed between Rust versions. Avoid them at the boundary.(). The unit type is not a C type. Omit the return type instead.
The compiler warns about many of these through the improper_ctypes lint. Treat that warning as a real bug report. Do not silence it without understanding why it fired.
Enums
A C enum is an integer, and its size is chosen by the compiler. The safest mapping is to declare the parameter as the integer type (usually c_int or c_uint) and define named constants:
use std::ffi::c_int;
pub const COLOR_RED: c_int = 0;
pub const COLOR_GREEN: c_int = 1;
pub const COLOR_BLUE: c_int = 2;
unsafe extern "C" {
fn set_color(c: c_int);
}Using a Rust enum with #[repr(C)] or #[repr(i32)] is possible, but it carries a risk. If C returns a value that is not one of your variants, creating that Rust enum value is undefined behavior. An integer plus constants cannot fail that way. You can convert to a real Rust enum later, with a TryFrom implementation that returns an error for unknown values.
Checking your work
Layout bugs are silent, so check them. A few habits catch most mistakes.
- Keep the C header open next to the Rust declaration and translate each parameter one by one.
- Add a size assertion for any type whose size you depend on, such as
const _: () = assert!(std::mem::size_of::<c_int>() == 4);. - Compile the C code with warnings on, and call a tiny C function from Rust that echoes its arguments. If the echo returns different values, the types disagree.
- Run tests under a tool like Miri where possible, and use a sanitizer on the C side.
Common errors
- Using
i32ori64forintorlong. Works on your machine, breaks on another target. - Using a reference for a pointer that can be null. Undefined behavior, and often invisible until the optimizer exploits it.
- Declaring a callback with
fninstead ofextern "C" fn. The calling convention is wrong. - Treating
c_charas always signed. On some platforms, such as ARM Linux, it is unsigned. Cast explicitly when you need a specific signedness. - Returning a wrongly-sized integer. On a 64-bit target, reading a 32-bit return value as 64 bits yields garbage in the upper half.
Exercise
A C library declares unsigned long total_bytes(const unsigned char *data, size_t len);. Write the Rust extern declaration. Then explain why using u64 as the return type is risky.
Show answer
The declaration is unsafe extern "C" { fn total_bytes(data: *const c_uchar, len: usize) -> c_ulong; }, with c_uchar and c_ulong imported from std::ffi. Using u64 is risky because C's unsigned long is 32 bits on 64-bit Windows and 64 bits on 64-bit Linux and macOS. A u64 return type would read the wrong number of bytes on Windows, while c_ulong follows the target platform.
Exercise
A C function int find(const char *key, const item **out); returns 0 on success and sets *out to a pointer to an item, or leaves it unchanged on failure. Declare it in Rust and write a safe-looking helper that returns Option<*const Item>, where Item is a #[repr(C)] struct.
Show answer
Declare fn find(key: *const c_char, out: *mut *const Item) -> c_int;. The helper starts with let mut p: *const Item = std::ptr::null();, calls find(key, &mut p) inside unsafe, and returns Some(p) when the result is 0 and None otherwise. The out-parameter is a pointer to a pointer, so its type is *mut *const Item.