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