Interoperability with C
Rust has full support for linking object files with a C calling convention. Similarly, you can export Rust functions and call them from C.
You can do it by hand if you want:
// Copyright 2022 Google LLC
// SPDX-License-Identifier: Apache-2.0
unsafe extern "C" {
safe fn abs(x: i32) -> i32;
}
fn main() {
let x = -42;
let abs_x = abs(x);
println!("{x}, {abs_x}");
}
We already saw this in the Safe FFI Wrapper exercise.
This assumes full knowledge of the target platform. Not recommended for production.
We will look at better options next.
-
The
"C"part of theexternblock tells Rust thatabscan be called using the C ABI (application binary interface). -
The
safe fn abspart tells Rust thatabsis a safe function. By default, extern functions are unsafe, but sinceabs(x)can’t trigger undefined behavior with anyx, we can declare it safe.