官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 靖边县| 海门市| 黎川县| 大厂| 柳河县| 普定县| 资源县| 普洱| 广河县| 仁化县| 齐齐哈尔市| 拜泉县| 定西市| 肇庆市| 永春县| 长阳| 林州市| 河间市| 攀枝花市| 故城县| 黎平县| 巴林右旗| 盐池县| 望奎县| 华宁县| 桃园县| 南漳县| 望奎县| 七台河市| 福清市| 民权县| 河源市| 柳州市| 泸定县| 滕州市| 海丰县| 新沂市| 高密市| 奉化市| 长治市| 攀枝花市|