FFI panic boundaries
Quick answer
Rust panics and foreign exceptions must not cross an incompatible ABI boundary. Exported functions should return documented status values for expected failures and have an explicit policy for unexpected panics.
Translate failures at the boundary
An unwinding Rust panic reaching a non-unwinding C ABI boundary causes an abort. catch_unwind can catch unwinding Rust panics within the boundary, but not aborting panics; a panic hook can still run. Foreign exceptions need a specifically designed ABI and runtime contract. In production, consider panic payload destruction and recovery of state as well. These local fixtures do not cross an actual foreign boundary.
extern "C" fn validate(n: u32) -> i32 { if n <= 100 { 0 } else { -1 } }fn main() { println!("{} {}", validate(4), validate(101)); }Expected stdout (not executed):
0 -1Expected invalid input is handled without panic.
fn main() { let result = std::panic::catch_unwind(|| 3u32 + 4); println!("{}", result.unwrap());}Expected stdout (not executed):
7A normal return becomes Ok. An unwinding panic may become Err; this fixture does not trigger a panic.
Common mistake
Do not promise catch_unwind catches every failure or foreign exception.
Try it yourself
Define distinct status codes for invalid input and an internal failure, and describe when a process abort is still possible.
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
FFI panic boundaries — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A Rust library uses panic=abort. Can catch_unwind convert all panics into C error statuses?
FFI panic boundaries — 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 extern "C" fn validate(n: u32) -> i32 { if n <= 100 { 0 } else { -1 } } fn main() { println!("{} {}", validate(4), validate(101)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
FFI panic boundaries — 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 fn main() { let result = std::panic::catch_unwind(|| 3u32 + 4); println!("{}", result.unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.