1 执行 cargo new hellolib --lib 创建库项目
修改 cargo.toml
[lib] name = "myfirst_rust_dll" #生成dll的文件名 crate-type = ["dylib"]
lib.rs
#[no_mangle] pub extern fn hello_rust(){ println!("Hello rust dll!"); }
执行: cargo build --release
生成了myfirst_rust_dll.dll
2、现在准备调用上面的myfirst_rust_dll.dll
执行 cargo new hello 创建二进制项目
修改 cargo.toml
[dependencies] libloading = "0.7"
main.rs
extern crate libloading; fn call_dynamic() -> Result<u32, Box<dyn std::error::Error>> { unsafe { let lib = libloading::Library::new("myfirst_rust_dll.dll")?; let func: libloading::Symbol<unsafe extern fn() -> u32> = lib.get(b"hello_rust")?; Ok(func()) } } fn main() { let _a =call_dynamic(); }
将myfirst_rust_dll.dll复制到hello目录下,在VSCode中调试,将输出:"Hello rust dll!"
或将myfirst_rust_dll.dll复制到debug目录下,在控制台中运行hello.exe ,也将输出:"Hello rust dll!"
参考:https://blog.yasking.org/a/rust-dll-clipboard.html
https://docs.rs/libloading/0.7.0/libloading/
https://blog.csdn.net/wowotuo/article/details/86251732