Skip to main content
Be Bitwise
RustAssembly Equivalents of Rust Patterns

FFI & Unsafe at the Boundary

Rust calls C, C calls Rust. The interop works because both can speak the same calling conventions and agree on memory layouts. We'll dig into what extern "C" functions actually look like in assembly, how unsafe blocks lower, and what crosses the boundary between safe and unsafe Rust.

extern "C" Functions

The extern "C" marker pins the calling convention to whatever C uses on this platform — System V AMD64 on Linux and macOS:

rust
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}
asm
add:
lea eax, [rdi+rsi] ; eax = a + b
ret

This is identical to the C version:

c
int add(int a, int b) {
return a + b;
}
asm
add:
lea eax, [rdi+rsi]
ret

Identical, line for line. #[no_mangle] keeps Rust from mangling the symbol — without it you'd be linking against _ZN7example3add17h... instead of plain add. extern "C" locks arguments into edi, esi per the C convention, not whatever shuffling Rust might do internally.

The examples here use the syntax every edition accepts. In the 2024 edition two of them change: #[no_mangle] must be written #[unsafe(no_mangle)], because two functions exporting the same symbol name is undefined behaviour the compiler can't check, and extern blocks must be written unsafe extern "C" { ... }. Both forms are accepted in every edition from Rust 1.82.

Calling C from Rust

rust
extern "C" {
fn strlen(s: *const u8) -> usize;
fn printf(fmt: *const u8, ...) -> i32;
}
fn example() {
unsafe {
let msg = b"Hello from Rust!\n\0";
let len = strlen(msg.as_ptr());
printf(b"Length: %zu\n\0".as_ptr(), len);
}
}
asm
example:
push rbx
; Call C's strlen
lea rdi, [rip+.Lmsg] ; Pointer to "Hello from Rust!\n"
call strlen ; C function, same calling convention
mov rbx, rax ; Save length
; Call C's printf
lea rdi, [rip+.Lfmt] ; Format string "Length: %zu\n"
mov rsi, rbx ; Length argument
xor eax, eax ; Number of vector args = 0 (variadic)
call printf
pop rbx
ret

Indistinguishable from what a C compiler would emit. The unsafe block costs nothing in instructions. Its job is to make the compiler accept raw pointer ops and foreign calls, not to add code.

Calling Rust from C

rust
// lib.rs
#[no_mangle]
pub extern "C" fn rust_process(data: *const i32, len: usize) -> i32 {
// Convert raw C data to a safe Rust slice
let slice = unsafe { std::slice::from_raw_parts(data, len) };
// Now use safe Rust
slice.iter().filter(|&&x| x > 0).sum()
}
c
// main.c
extern int rust_process(const int *data, size_t len);
int main() {
int arr[] = {1, -2, 3, -4, 5};
int result = rust_process(arr, 5);
printf("Result: %d\n", result);
return 0;
}

The assembly for rust_process:

asm
rust_process:
; rdi = data pointer, rsi = len
; This IS the safe Rust iterator code - optimized as usual
xor eax, eax ; sum = 0
test rsi, rsi
je .done
.loop:
mov ecx, DWORD PTR [rdi] ; Load element
test ecx, ecx
jle .skip ; Filter: skip if <= 0
add eax, ecx ; Sum positive values
.skip:
add rdi, 4
dec rsi
jnz .loop
.done:
ret

From C's side, it's a plain function taking a pointer and a length. From Rust's side, the unsafe boundary converts those raw bytes into a safe slice, after which the iterator code enjoys the usual Rust guarantees.

How unsafe Blocks Compile

Compare the safe and unsafe versions of the same operation:

rust
fn safe_index(slice: &[i32], i: usize) -> i32 {
slice[i] // Bounds check included
}
fn unsafe_index(slice: &[i32], i: usize) -> i32 {
unsafe { *slice.get_unchecked(i) } // No bounds check
}
asm
safe_index:
cmp rdx, rsi ; Compare index with length
jae .panic_bounds_check ; If index >= length, panic
mov eax, DWORD PTR [rdi+rdx*4] ; Load the element
ret
.panic_bounds_check:
; Call panic machinery
call core::panicking::panic_bounds_check
unsafe_index:
mov eax, DWORD PTR [rdi+rdx*4] ; Load the element directly
ret

The unsafe version drops the bounds check — that one cmp and jae. The actual memory access is identical. unsafe doesn't change codegen for any operation; it just lets you use operations the compiler can't verify on its own.

Struct Layout Compatibility

FFI demands a predictable struct layout. Rust's default layout is unspecified — the compiler is free to reorder fields for cache or alignment wins. #[repr(C)] pins fields to C's rules:

rust
#[repr(C)]
pub struct Point {
pub x: f64,
pub y: f64,
}
#[no_mangle]
pub extern "C" fn distance(a: *const Point, b: *const Point) -> f64 {
unsafe {
let dx = (*a).x - (*b).x;
let dy = (*a).y - (*b).y;
(dx * dx + dy * dy).sqrt()
}
}
asm
distance:
; rdi = pointer to Point a, rsi = pointer to Point b
movsd xmm0, QWORD PTR [rdi] ; a.x (offset 0)
subsd xmm0, QWORD PTR [rsi] ; a.x - b.x
movsd xmm1, QWORD PTR [rdi+8] ; a.y (offset 8)
subsd xmm1, QWORD PTR [rsi+8] ; a.y - b.y
mulsd xmm0, xmm0 ; dx * dx
mulsd xmm1, xmm1 ; dy * dy
addsd xmm0, xmm1 ; dx*dx + dy*dy
sqrtsd xmm0, xmm0 ; sqrt(...)
ret

With #[repr(C)], field offsets match a C compiler exactly: x at offset 0, y at offset 8. Without it, Rust might reorder or pad fields and quietly break the interop.

Passing Complex Types Across FFI

Types without a C equivalent — String, Vec, Option — need converting at the boundary:

rust
// Expose a Rust String as a C-compatible pointer + length
#[no_mangle]
pub extern "C" fn get_greeting(name: *const u8, name_len: usize, out_ptr: *mut *const u8, out_len: *mut usize) {
let name_slice = unsafe { std::slice::from_raw_parts(name, name_len) };
let name_str = std::str::from_utf8(name_slice).unwrap_or("stranger");
let greeting = format!("Hello, {}!", name_str);
// Leak the String so C can use the pointer (C must call free_greeting later).
// The length handed back must be the greeting's, not the name's:
// free_greeting rebuilds the Box from it.
let len = greeting.len();
let ptr = Box::into_raw(greeting.into_boxed_str()) as *const u8;
unsafe {
*out_ptr = ptr;
*out_len = len;
}
}
#[no_mangle]
pub extern "C" fn free_greeting(ptr: *mut u8, len: usize) {
unsafe {
let _ = Box::from_raw(std::slice::from_raw_parts_mut(ptr, len));
// Box is dropped here, freeing the memory
}
}

The assembly at the boundary is plain pointer juggling. The interesting work is the Rust code that formats the string, and that compiles the same whether it sits behind an FFI boundary or in a plain Rust function.

The pointer and the length travel as a pair, and they have to describe the same allocation. Hand back the name's length instead of the greeting's and free_greeting rebuilds a Box<[u8]> of the wrong size, then frees it with the wrong layout. That's undefined behaviour, and in a real program it's the kind of heap corruption an attacker goes looking for. CString::into_raw and CString::from_raw avoid the length altogether if the C side is happy with a NUL-terminated string.

Panics are the other hazard at this seam. A panic can't unwind into C code. Since Rust 1.81 a panic that reaches the edge of an extern "C" function aborts the process instead of unwinding into the caller, so if the function can fail, catch it with std::panic::catch_unwind and turn it into an error code before returning to C.

Comparing Rust's unsafe to C

rust
// Rust: unsafe block for raw pointer dereference
fn example(ptr: *const i32) -> i32 {
unsafe { *ptr }
}
c
// C: all pointer access is implicitly "unsafe"
int example(const int *ptr) {
return *ptr;
}
asm
; Both compile to:
example:
mov eax, DWORD PTR [rdi]
ret

Identical machine code. The split is in what the compiler insists on before emitting it. Rust makes you mark the dereference unsafe. C lets you dereference any pointer anywhere with zero compile-time pushback.

Linking Rust and C

Build a mixed Rust + C project:

bash
# Compile Rust library
rustc --crate-type=staticlib lib.rs -o libmyrust.a
# Ask rustc which system libraries the static library needs
rustc --crate-type=staticlib lib.rs -o libmyrust.a --print native-static-libs
# Compile and link C code with Rust library, adding whatever that printed
gcc main.c -L. -lmyrust -lpthread -ldl -o program

Rust's standard library leans on threading and dynamic loading under the hood, so the C link has to pull in the system libraries that provide them. The exact list depends on the target, which is why --print native-static-libs exists. On glibc 2.34 and later, libpthread and libdl are folded into libc and the extra flags are harmless leftovers. The linker fuses Rust and C object code into one binary and resolves the cross-language symbol references.

Key Takeaways

  1. extern "C" produces identical assembly to C. Calling convention, argument passing, return values — same in both directions.

  2. unsafe removes compile-time checks, not runtime code. The generated assembly differs only by what's missing: bounds checks, null checks. Nothing extra is added.

  3. #[repr(C)] matches C struct layout. Field order, padding, and alignment follow C's rules, so structs cross the FFI boundary cleanly.

  4. The FFI boundary is where you convert types. Rich Rust types — String, Vec, Option — get translated into pointer/length pairs and sentinel values at the seam. Inside either language, code compiles as normal.

  5. Rust and C often produce the same machine code. For simple equivalent operations like the ones here, the output is frequently identical, since both go through an optimising backend and the same calling convention. Where they differ, it's usually checks Rust adds in safe code (bounds checks, overflow checks in debug builds) or aliasing information that lets Rust optimise a little harder. Most of Rust's safety lives in the compiler; the generated code knows nothing about it.