在Rust中调用Rust动态库
2020/07/24
posted in
Rust
2020/07/24
posted in
Rust
首先我们先在Cargo.toml
中添加相关配置
[[bin]]
name = "master"
path = "src/master/master.rs"
[lib]
name = "speaker"
path = "src/plugins/speaker.rs"
crate-type = ["cdylib"]
[dependencies]
libloading = "*"
其中, speaker
是动态库, master
是调用动态库的主程序
#[no_mangle]
pub extern fn run() {
println!("Hello, speaker!");
}
#[no_mangle]
表示禁用name mangling
, 它表示以原始的函数名编译函数, 因为在一些支持重载的语言中, 编译的函数名并不是在代码中声明的函数名, 而是函数名加参数类型.
extern crate libloading as lib;
fn call_dynamic() -> Result<u32, Box<dyn std::error::Error>> {
let lib = lib::Library::new("/Data/Rust/learn4libloading/target/debug/libspeaker.dylib")?;
unsafe {
let func: lib::Symbol<unsafe extern fn() -> u32> = lib.get(b"run")?;
Ok(func())
}
}
fn main() {
println!("Hello, master!");
let rst = call_dynamic();
match rst {
Ok(i) => println!("{}", i),
Err(e) => println!("{}", e)
}
}