C ABI and repr C
Quick answer
An application binary interface specifies how compiled code calls functions and passes data. Rust's default ABI is not a stable foreign interface; use an agreed C ABI and compatible types for a C boundary.
Match layout and calling convention
extern "C" selects the target's C calling convention. repr(C) applies C-compatible layout rules to a struct, but its fields must also be suitable for the interface. Padding and alignment can vary by target; a struct's bytes are not a portable wire format. Specify fixed-width integers in the matching C header. Rust 2024 requires unsafe extern blocks for foreign declarations.
#[repr(C)]struct Pair { x: u32, y: u32 }fn main() { let p = Pair { x: 2, y: 3 }; println!("{}", p.x + p.y);}Expected stdout (not executed):
5The intended C declaration uses two uint32_t fields; confirm offsets and alignment on both sides.
extern "C" fn add(a: u32, b: u32) -> u32 { a.wrapping_add(b) }fn main() { let f: extern "C" fn(u32, u32) -> u32 = add; println!("{}", f(2, 4));}Expected stdout (not executed):
6This local call uses the declared ABI and signature; no foreign symbol is linked.
Common mistake
Do not assume repr(C) makes String, Vec or arbitrary Rust enums portable across languages.
Try it yourself
Write a matching C declaration for Pair using stdint.h and explain what must be verified on each target.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
C ABI and repr C — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A repr(C) struct embeds a Rust String. Can it be passed as a portable C record without further design?
C ABI and repr C — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust #[repr(C)] struct Pair { x: u32, y: u32 } fn main() { let p = Pair { x: 2, y: 3 }; println!("{}", p.x + p.y); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
C ABI and repr C — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust extern "C" fn add(a: u32, b: u32) -> u32 { a.wrapping_add(b) } fn main() { let f: extern "C" fn(u32, u32) -> u32 = add; println!("{}", f(2, 4)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.