Sub topic 2
Sharing structs with `#[repr(C)]`
This chapter assumes basic Rust ownership, borrowing, Result, Cargo, C pointers, and unsafe Rust.
Matching a C struct
The C application binary interface (ABI) defines how functions and data are laid out in memory. Rust's default struct layout can change, so use #[repr(C)] when C reads or writes a Rust struct.
/* src/point.h */
typedef struct {
double x;
double y;
} point;
double point_distance(const point *a, const point *b);#[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) }
}#[repr(C)] preserves field order, alignment, and representation expected by C. The wrapper accepts references, so callers cannot pass null pointers through this API. The unsafe block remains necessary because Rust cannot verify the foreign function's behavior.
Linking against C libraries
A declaration tells Rust a function exists. The linker must still find its implementation. For a system library, use a link attribute:
#[link(name = "m")]
unsafe extern "C" {
fn sqrt(value: f64) -> f64;
}The m name refers to the platform's math library. Library names and availability vary by operating system.
Compiling C with `build.rs`
For C source in your project, the cc crate can compile and link it automatically.
# Cargo.toml
[build-dependencies]
cc = "1"// build.rs
fn main() {
cc::Build::new()
.file("src/point.c")
.compile("point");
println!("cargo:rerun-if-changed=src/point.c");
}The C file must include point.h and define point_distance. Cargo runs build.rs before linking the Rust crate.
Opaque handles and allocation rules
Some C libraries hide their structs and return handles. Model such a handle as a private, non-null pointer. The library that allocates it must also free it.
A Rust wrapper should call the matching C destructor exactly once in Drop. Do not move a C allocation into Rust's allocator or derive Copy for an owning wrapper. If C requires a special cleanup function, Rust must use that function rather than free.
Exercise
Why is #[repr(C)] required before passing Point to C?
Show answer
Rust's default field layout is not an ABI promise. #[repr(C)] makes the layout match C's struct layout.