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

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.

主站蜘蛛池模板: 含山县| 桐乡市| 丹巴县| 廉江市| 灌云县| 遵化市| 德庆县| 平泉县| 郑州市| 石棉县| 张家港市| 富宁县| 景泰县| 龙南县| 顺义区| 太和县| 阳朔县| 白水县| 板桥市| 娄烦县| 延寿县| 建德市| 五河县| 富阳市| 启东市| 嫩江县| 尚志市| 自贡市| 京山县| 莆田市| 庐江县| 开远市| 嵊州市| 通河县| 师宗县| 盐城市| 喀什市| 无棣县| 察哈| 威信县| 响水县|