ide*_*n42 3 namespaces ffi rust
在Rust中,extern C
函数可以在外部作用域中声明:
#[link(name = "some_lib")]
extern "C" {
pub fn foo(path: *const c_char);
pub fn bar(path: *const c_char);
pub fn baz(path: *const c_char);
pub fn fez(path: *const c_char);
}
Run Code Online (Sandbox Code Playgroud)
虽然可以接受,但每个功能都需要直接访问foo()
bar()
...等.
是否可以使用公共前缀来访问它们?
封装如何工作的示例:
namespace some_lib {
#[link(name = "some_lib")]
extern "C" {
pub fn foo(path: *const c_char);
// ... etc ...
}
}
fn some_rust_function() {
unsafe {
some_lib::foo(); // <-- example usage
}
}
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
只需使用一个模块.
mod ffi {
extern "C" {
pub fn exit(_: i32) -> !;
}
}
fn main() {
unsafe { ffi::exit(1); }
}
Run Code Online (Sandbox Code Playgroud)