Sub topic 5
Sharing structs with #[repr(C)]
This chapter assumes you can already declare and call a C function from unsafe Rust, and that you know the C types in std::ffi. It builds on the earlier chapters on extern blocks and C-compatible types.
Why Rust structs need a layout promise
C compilers lay out struct fields in declaration order and add padding to meet alignment rules. Rust makes no such promise for its own structs. The compiler may reorder fields to save space, and that choice can change between compiler versions.
If C reads memory that Rust laid out differently, you get wrong values or undefined behavior, and the compiler gives you no error. The attribute #[repr(C)] tells Rust to use the C layout rules for a type: fields in declaration order, with C-style padding.
A struct shared with C
Here is the C side from the running example:
/* src/point.h */
typedef struct {
double x;
double y;
} point;
double point_distance(const point *a, const point *b);The matching Rust type and a safe wrapper:
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Point {
pub x: f64,
pub y: f64,
}
unsafe extern "C" {
fn point_distance(a: *const Point, b: *const Point) -> f64;
}
pub fn distance(a: &Point, b: &Point) -> f64 {
unsafe { point_distance(a, b) }
}Three points about this code:
- Field types match in order and meaning. C
doubleis Rustf64. - The extern block takes
*const Point, which matchesconst point *. distanceaccepts references. A Rust reference is never null and always points to a validPoint, so it is safe to coerce to the pointers C expects.
Padding and alignment
Padding is the main reason layouts differ. Consider this C struct:
typedef struct {
uint8_t tag;
uint32_t value;
} header;A uint32_t needs 4-byte alignment, so C puts three padding bytes after tag. The Rust equivalent is checked below.
use std::mem::{align_of, size_of};
#[repr(C)]
struct Header {
tag: u8,
value: u32,
}
fn main() {
println!("{} {}", size_of::<Header>(), align_of::<Header>());
}This prints 8 4: one byte for tag, three bytes of padding, and four bytes for value. You never write the padding yourself.
Checking the layout at compile time
A mismatch with the C side is easy to introduce when someone edits a header. You can catch it with a compile-time assertion that uses sizes from the C definition:
use std::mem::{align_of, size_of};
#[repr(C)]
pub struct Point {
pub x: f64,
pub y: f64,
}
const _: () = assert!(size_of::<Point>() == 16);
const _: () = assert!(align_of::<Point>() == 8);
fn main() {
println!("layout ok");
}If the sizes disagree, the build fails instead of the program misbehaving at run time.
Field rules
Every field of a #[repr(C)] struct must itself be FFI-safe. Follow these rules:
- Use
std::ffitypes or fixed-size integers such asu32, floats, raw pointers, and other#[repr(C)]structs. - Do not use
String,Vec, orBoxas fields. C does not understand their layout. - Use
*const Tor*mut Tfor pointers inside the struct.Option<&T>also works for a nullable pointer. - Fieldless enums need
#[repr(C)]or an explicit integer repr such as#[repr(u32)]. If C returns a value that is not one of your variants, you get undefined behavior. For values you do not control, receive a plain integer and convert it yourself.
Passing by pointer or by value
A #[repr(C)] struct can also be passed by value if the C function takes it by value. The Rust side must then match the C declaration exactly. Pointers are simpler and less error-prone for structs larger than a couple of fields, so prefer them when you can choose.
Exercise
A C struct is typedef struct { uint8_t a; uint16_t b; uint8_t c; } s;. What are its size and alignment under C layout rules, and what attribute makes the Rust version match?
Show answer
Field a takes 1 byte, then 1 padding byte aligns b to 2. b takes 2 bytes, c takes 1 byte, and 1 trailing padding byte rounds the size to a multiple of 2. The size is 6 and the alignment is 2. Declaring the Rust struct with #[repr(C)] and the same fields (u8, u16, u8) in the same order gives the same layout.