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

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.

主站蜘蛛池模板: 阳西县| 张家口市| 日土县| 开化县| 武胜县| 张家川| 邮箱| 和龙市| 个旧市| 开鲁县| 藁城市| 阿合奇县| 绍兴市| 烟台市| 平顶山市| 屯昌县| 阿拉善左旗| 漠河县| 买车| 九龙坡区| 河南省| 威信县| 富川| 温州市| 兴宁市| 黄龙县| 时尚| 宿州市| 衡阳县| 吴堡县| 武山县| 蓝田县| 鄢陵县| 泸水县| 海阳市| 昂仁县| 长葛市| 南城县| 吴江市| 武山县| 淮滨县|