Rust 语言的库代码可以编译为 Windows 系统的 .dll 文件或 Linux 系统的 .so 文件。Rust 提供了对动态链接库(shared library,共享库)的良好支持,可以生成这些共享库以供 C、C++ 或其他语言使用。
1 编译为 Windows .dll 文件 在 Cargo.toml 中,需要指定 crate-type 为 cdylib 或 dylib:
[lib]
name = "mylib"
crate-type = ["cdylib"]
然后编写 Rust 代码(src/lib.rs):
#[no_mangle]
pub extern "C" fn add(a: i32, b: i32) -> i32 {
a + b
}
使用 cargo build –release 进行编译后,在 target/release/ 目录下会生成 mylib.dll 文件。
2 编译 Linux .so 文件
在 Linux 上,同样的 Cargo.toml 适用于 .so 文件,Rust 会自动根据目标平台生成 .so:
[lib]
name = "mylib"
crate-type = ["cdylib"]
Rust 代码保持不变,使用 cargo build –release,Rust 会在 target/release/ 目录下生成 libmylib.so。
3 crate-type的值
- cdylib:生成 C 兼容的动态库,适用于其他语言(如 Python、C++)调用。
- dylib:Rust 专用动态库,带有 Rust 运行时,通常用于 Rust 内部。
如果是给其他语言(如 C 或 Python)使用,推荐 cdylib,因为它不会带 Rust 运行时。
4 跨平台编译(交叉编译)
Rust 允许通过 –target 选项进行交叉编译。 Windows 交叉编译 Linux .so:
cargo build --release --target x86_64-unknown-linux-gnu
Linux 交叉编译 Windows .dll:
cargo build --release --target x86_64-pc-windows-gnu
5 示例:C 语言调用 Rust 共享库
在 C 代码中调用 Rust 编写的 add 函数:
#include <stdio.h>
extern int add(int a, int b);
int main() {
printf("Result: %d\n", add(2, 3));
return 0;
}
然后
- Windows 需链接 mylib.dll
- Linux 需链接 libmylib.so
结论
Rust 可以生成 .dll 和 .so 文件,并且可以通过 #[no_mangle] 和 extern “C” 让 Rust 代码能被 C 语言或其他语言调用。使用 cargo build –release 可编译出目标共享库,并可结合 –target 进行跨平台编译。