- Hands-On Data Structures and Algorithms with Rust
- Claus Matzinger
- 241字
- 2021-07-02 14:11:47
FFI
The Foreign Function Interface (FFI) is Rust's way of calling into other native libraries (and vice versa) using a simple keyword: extern. By declaring an extern function, the compiler knows that, either an outside interface needs to be bound via the linker (import) or, that the declared function is to be exported so other languages can make use of it (export).
In addition to the keyword, the compiler and linker have to get a hint of what type of binary layout is expected. That's why the usual extern declaration looks as follows:
extern "C" {
fn imported_function() -> i32;
}
#[no_mangle]
pub extern "C" fn exported_function() -> i32 {
42
}
This allows a C library function to be called from within Rust. However, there's one caveat: the calling part has to be wrapped in an unsafe section. The Rust compiler cannot guarantee the safety of an external library so it makes sense to be pessimistic about its memory management. The exported function is safe, and by adding the #[no_mangle] attribute, there is no name mangling, so it can be found using its name.
In order to use libraries for specialized algorithms available in a C/C++ library, there is a tool that generates suitable structures, extern "C" declarations, and data types, called rust-bindgen. Find out more at https://github.com/rust-lang-nursery/rust-bindgen. These interoperability capabilities make Rust code available to legacy software or for use in a vastly different context, such as web frontends.