Sub topic 3
Matching C types in Rust
This chapter assumes you can write a basic extern block and call a C function from unsafe Rust, as in the previous chapter. It also assumes you know what a raw pointer is. Here you will learn how to choose the Rust type that matches each C type in a declaration.
Why the types must match
Rust cannot read a C header when you write an extern block. It trusts whatever signature you type. If your declaration disagrees with the real C function, the compiler gives no error. The program may crash, or it may quietly return wrong values. Matching types is therefore your job.
C types also vary by platform. An int is usually 32 bits, but a long is 64 bits on 64-bit Linux and 32 bits on 64-bit Windows. The std::ffi module provides aliases such as c_int and c_long, and each alias matches the C type on the platform you compile for.
The core mappings
| C type | Rust type |
|---|---|
| `int`, `unsigned int` | `c_int`, `c_uint` |
| `long`, `unsigned long` | `c_long`, `c_ulong` |
| `char` | `c_char` |
| `double`, `float` | `f64`, `f32` |
| `size_t` | `usize` |
| `bool` (`_Bool`) | `bool` |
| `const T *` | `*const T` |
| `T *` | `*mut T` |
| `void *` | `*mut c_void` |
double and float have fixed sizes, so f64 and f32 are safe. In practice size_t matches usize on mainstream platforms. The c_char type is signed on some targets and unsigned on others, so do not assume it is i8.
A worked example
This program calls labs, which takes a long. It also calls memcmp, which takes two void * pointers and a size_t.
use std::ffi::{c_int, c_long, c_void};
unsafe extern "C" {
fn labs(n: c_long) -> c_long;
fn memcmp(a: *const c_void, b: *const c_void, n: usize) -> c_int;
}
fn main() {
let a = [1u8, 2, 3];
let b = [1u8, 2, 4];
let big = unsafe { labs(-40) };
let order = unsafe { memcmp(a.as_ptr().cast(), b.as_ptr().cast(), a.len()) };
println!("{big} {}", order < 0);
}It prints 40 true. The cast() method changes *const u8 into *const c_void. The compiler infers the target type from the parameter. C only promises that memcmp returns a negative number here, not a specific one, so the program tests the sign instead of comparing to -1.
Choosing a type: a quick decision path
Types to keep out of signatures
Some Rust types have no defined C layout. Do not use them in extern signatures:
String,Vec<T>,&str, and slices. A&stror&[T]is a pointer plus a length, which C does not expect. Pass a pointer and ausizelength separately.- Tuples and ordinary Rust enums with data. Their layout is unspecified.
u128andi128. Their ABI is not stable across platforms.
Some wrapped types are allowed. Option<extern "C" fn(...)> and Option<&T> have the same layout as a nullable C pointer, with None standing for NULL. NonNull<T> is a pointer that cannot be null.
For C enums, declare the parameter as the integer type C uses, such as c_int. Then define Rust constants for the values. If C returns a value that is not in your Rust enum, you have undefined behavior, so a plain integer is safer.
Common errors
- Using
i32forlong. It works on Linux and breaks on Windows. Usec_long. - Treating
*const Tas a promise of validity. A raw pointer can be null or dangling. Check before you dereference one that came from C. - Passing a pointer to a temporary that is dropped before the call ends.
- Changing the declaration to make a compile error go away. The error usually means your argument has the wrong type.
Exercise
A C function is declared as unsigned long total(const unsigned int *values, size_t count);. Write the Rust declaration inside an unsafe extern "C" block, and explain why you should not use u64 for the return type.
Show answer
fn total(values: *const c_uint, count: usize) -> c_ulong;. On 64-bit Windows, unsigned long is 32 bits, so u64 would not match there. c_ulong follows the target platform.