RRust By Example
advancedUnsafe

FFI with C

Call C functions from Rust using FFI.

FFI with C

Call C functions from Rust using FFI.

Difficulty

Advanced

Code

rust
extern "C" {
    fn abs(input: i32) -> i32;
}

fn main() {
    unsafe {
        println!("abs(-3) = {}", abs(-3));
        println!("abs(42) = {}", abs(42));
    }
}

Explanation

This example demonstrates how to use ffi with c in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the unsafe category to build a complete understanding of this topic.

More Unsafe Examples