Sub topic 5
Sharing structs with #[repr(C)]
This chapter assumes you can read basic C, know Rust structs and references, and have already declared and called a C function from an unsafe block. It covers how to make a Rust struct have the same memory layout as a C struct, so you can pass it to C and receive it back.
Why the default layout is not enough
C fixes how a struct is laid out. Fields appear in declaration order, each field sits at an offset that satisfies its alignment, and the compiler may add padding between fields and at the end.
Rust's default representation, repr(Rust), makes no such promise. The compiler may reorder fields to shrink the struct, and the order can change between compiler versions. If you pass a default-layout struct to C, C reads the bytes at the offsets its header describes, and those offsets may not match.
#[repr(C)] tells Rust to lay the struct out by the C rules for the target platform. The struct then has the same size, alignment, and field offsets as the equivalent C struct.
Mirroring a C struct
Here is a C library with a struct and a function that takes pointers to it. This is the same library the linking chapters use.
/* src/point.h */
typedef struct {
double x;
double y;
} point;
double point_distance(const point *a, const point *b);
/* src/point.c */
#include <math.h>
#include "point.h"
double point_distance(const point *a, const point *b) {
double dx = a->x - b->x;
double dy = a->y - b->y;
return sqrt(dx * dx + dy * dy);
}The Rust side declares a struct with the same fields in the same order, and marks it #[repr(C)].
#[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 details matter here.
- A Rust
f64is an IEEE 754 double, which is what C'sdoubleis on all common platforms, so nostd::ffialias is needed. - The safe function
distanceis sound because a Rust reference is non-null, aligned, and points to a livePoint. C only reads through the pointers and does not keep them after returning. - Rust coerces
&Pointto*const Pointat the call, so no cast is needed.
This code compiles on its own, but linking fails until the C file is built into the program. The build script chapter shows how to do that.
Padding and offsets
Padding is where hand-written mirrors go wrong, so it helps to see it. This program prints the layout Rust chose for a repr(C) struct. It uses offset_of!, available since Rust 1.77.
use std::mem::{align_of, offset_of, size_of};
#[repr(C)]
struct Mixed {
a: u8,
b: u32,
c: u16,
}
fn main() {
println!("size={} align={}", size_of::<Mixed>(), align_of::<Mixed>());
println!(
"a={} b={} c={}",
offset_of!(Mixed, a),
offset_of!(Mixed, b),
offset_of!(Mixed, c)
);
}On common 32-bit and 64-bit platforms it prints:
size=12 align=4
a=0 b=4 c=8The u32 needs 4-byte alignment, so three padding bytes follow a. The whole struct is rounded up to a multiple of its alignment, so two more bytes follow c. With default repr(Rust), the compiler is free to put b first and shrink the struct to 8 bytes. A C library compiled against the header would still expect 12.
Checking the layout at compile time
A mirror can drift from the header when someone edits one side and not the other. You can pin the layout with constant assertions, which fail the build instead of corrupting memory at run time.
use std::mem::{align_of, offset_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);
const _: () = assert!(offset_of!(Point, y) == 8);
fn main() {
println!("layout ok");
}The numbers come from the C side. For larger structs, a C test that prints sizeof and offsetof values, or generating the Rust declarations with bindgen (a later chapter), is more reliable than counting by hand.
What can go inside a repr(C) struct
Every field of a repr(C) struct should itself have a defined C layout. These are safe choices:
- Fixed-size integers and floats, and the
std::ffialiases such asc_int,c_long, andc_charwhen the C side usesint,long, orchar. - Raw pointers (
*const T,*mut T), including pointers to otherrepr(C)structs. Option<NonNull<T>>,Option<&T>, andOption<extern "C" fn(...)>, which Rust guarantees use the null pointer forNone.- Fixed-size arrays such as
[u8; 16], which match C arrays embedded in a struct. - Other
repr(C)structs, nested by value. bool, which matches C's_Bool(boolwith<stdbool.h>).
These do not belong in a struct you share with C:
String,Vec<T>,Box<T>,&str, and slices. Their layouts are not defined, and C cannot free or read them correctly. Use a pointer and a length instead.- Tuples, and enums that carry data. Their layouts are not defined.
- Trait objects (
dyn Trait), which are fat pointers.
Enums, unions, and other representations
A fieldless enum can be shared with C by adding #[repr(C)], which gives it the size of a C int, or by choosing an exact integer type such as #[repr(u8)] or #[repr(i32)].
use std::ffi::c_int;
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Color {
Red = 0,
Green = 1,
Blue = 2,
}
#[repr(C)]
pub struct Pixel {
pub color: Color,
pub alpha: c_int,
}The other representations you may meet:
| Attribute | Effect | Typical use |
|---|---|---|
| `#[repr(Rust)]` (default) | Layout unspecified, fields may be reordered | Pure Rust types |
| `#[repr(C)]` | C field order, padding, and alignment | Structs, unions, and enums shared with C |
| `#[repr(transparent)]` | Same layout and ABI as its single non-zero-sized field | Newtype around `c_int` or a pointer |
| `#[repr(C, packed)]` | C order with no padding | Matching `__attribute__((packed))` structs |
| `#[repr(u8)]`, `#[repr(i32)]` | Fixed integer type for an enum | Enums with a known C width |
#[repr(C)] union works like a C union. Reading a union field requires unsafe, because Rust cannot know which field was last written.
For packed structs, never create a reference to a field. A reference to a misaligned field is undefined behavior. Copy the value out (let x = s.field;) or use &raw const s.field and read_unaligned.
C bitfields (unsigned flag : 1;) have no Rust equivalent. Their layout is implementation-defined, so the usual approach is to treat the storage as an integer and write accessors, or to let bindgen generate them.
Passing structs by pointer and by value
Passing a pointer, as point_distance does, is the safest choice because only the address crosses the boundary. A repr(C) struct can also be passed or returned by value in an extern "C" function. Rust then follows the platform's C calling convention for that struct, which can mean registers on one target and memory on another. This works when your declaration exactly matches the C signature, and a mismatch in field types or count gives garbage without any error.
Other rules for pointers to structs:
- C may write through a
*mut Pointonly if you got it from a&mut Pointor an owned value, never from a shared reference. - C should not keep the pointer after the call unless you have arranged for the Rust value to stay alive and unmoved. The ownership chapter covers that.
- A
Pointinitialized in Rust is fully initialized. For a struct C fills in, useMaybeUninit<T>and callassume_initonly after C reports success.
use std::mem::MaybeUninit;
#[repr(C)]
#[derive(Debug)]
pub struct Point {
pub x: f64,
pub y: f64,
}
// Stand-in for a C function that fills in a struct and returns 0 on success.
unsafe fn fake_fill(out: *mut Point) -> i32 {
unsafe { out.write(Point { x: 1.0, y: 2.0 }) };
0
}
fn main() {
let mut slot = MaybeUninit::<Point>::uninit();
let rc = unsafe { fake_fill(slot.as_mut_ptr()) };
if rc == 0 {
let p = unsafe { slot.assume_init() };
println!("{p:?}");
}
}Calling assume_init before C has written the fields, or after C has failed, is undefined behavior.
Common mistakes
- Forgetting
#[repr(C)]. The code compiles, may even work by luck, and breaks after a compiler update. - Changing field order. Fields must appear in the same order as the C declaration.
- Using
i32forlong.longis 32 bits on Windows and 64 bits on 64-bit Linux and macOS. Usec_longso the width follows the platform. - Mirroring a struct with a flexible array member (
char data[];). Rust cannot represent it directly. Declare the fixed part and compute the pointer to the trailing data by hand. - Trusting a hand-written mirror forever. Add the compile-time assertions shown above, or generate the struct with bindgen.
Exercise
A C header declares struct header { uint8_t kind; uint32_t length; uint16_t flags; };. You write struct Header { kind: u8, length: u32, flags: u16 } in Rust without any attribute and pass &Header to C. Name two things that can go wrong, then give the corrected declaration and the size you expect on a typical platform.
Show answer
Without #[repr(C)] the compiler may reorder the fields, so C reads length and flags from the wrong offsets. The size may also differ from C's, so C can read or write outside the struct. The corrected declaration is #[repr(C)] struct Header { kind: u8, length: u32, flags: u16 }. With C layout, kind is at offset 0, three padding bytes follow, length is at offset 4, flags is at offset 8, and two tail padding bytes round the size to 12, with alignment 4. Add const _: () = assert!(size_of::<Header>() == 12); to catch drift.