Start with the idea
extern "C" selects the C calling convention and #[repr(C)] fixes field order so a struct matches its C counterpart. Every call is unsafe because the compiler cannot see the other side, and ownership must be agreed explicitly — who allocates, who frees, and how long a borrowed pointer stays valid.
An FFI boundary is a contract shared by two languages. The ABI determines how arguments and return values cross the call; #[repr(C)] helps a Rust struct follow C field order and padding rules for the target. It does not make every Rust type valid for C: String, Vec, and Rust enums without an explicit representation need a deliberate interface. Prefer fixed-width integer types where the C declaration requires them and check the target's definitions for size_t, pointers, and alignment.
In the example, abs takes and returns a C int; the Rust declaration must match the actual C header on that target.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.