与 C 的互操作性

Rust 对使用 C 调用约定链接目标文件提供了完整的支持。同样地,你可以导出 Rust 函数并从 C 中调用它们。

如果你愿意的话,你可以手工完成它:

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.

这假设对目标平台拥有充分的了解,不建议用于生产环境。

接下来我们将探讨更好的选择。

  • The "C" part of the extern block tells Rust that abs can be called using the C ABI (application binary interface).

  • The safe fn abs part tells that Rust that abs is a safe function. By default, extern functions are considered unsafe, but since abs(x) is valid for any x, we can declare it safe.