How does Rust FFI (Foreign Function Interface) work with C?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized Rust deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
Rust can call C functions and be called from C using its FFI. To call C from Rust, declare an extern "C" block with the function signatures: extern "C" { fn strlen(s: *const c_char) -> usize; }. Calling these is unsafe because Rust cannot verify C's memory safety. Link the C library via build.rs (using the cc crate) or #[link(name = "mylib")]. Use #[repr(C)] on structs to ensure they have C-compatible memory layout. To expose Rust functions to C, annotate with #[no_mangle] (prevents name mangling) and extern "C": #[no_mangle] pub extern "C" fn my_func() -> i32 { 42 }. The bindgen crate auto-generates Rust FFI bindings from C header files, and cbindgen generates C headers from Rust. Always use std::ffi types (CStr, CString) for string interop.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Rust codebase.
Previous
What are the rules for writing correct unsafe Rust?
Next
What is procedural macro metaprogramming with syn, quote, and proc_macro2?
More Rust Questions
View all →- Advanced What are zero-cost abstractions and monomorphization in Rust?
- Advanced What are Pin<T> and Unpin in Rust async programming?
- Advanced How does the async runtime work internally in Rust (Waker, Poll, Executor)?
- Advanced What are the rules for writing correct unsafe Rust?
- Advanced What is procedural macro metaprogramming with syn, quote, and proc_macro2?