linux

Linux系统如何调用Rust编写的库

小樊
65
2025-07-11 10:58:18
栏目: 编程语言

在Linux系统中,要调用Rust编写的库,你需要遵循以下步骤:

  1. 编写Rust库代码并编译为静态库或动态库。

首先,你需要编写Rust库代码。创建一个新的Rust库项目:

cargo new --lib my_rust_lib
cd my_rust_lib

lib.rs文件中编写你的库代码。例如:

#[no_mangle]
pub extern "C" fn hello_from_rust() {
    println!("Hello from Rust!");
}

接下来,编译库为静态库(.a)或动态库(.so)。在Cargo.toml文件中添加以下内容:

[lib]
name = "my_rust_lib"
crate-type = ["cdylib"] # 生成动态库

然后运行cargo build命令编译库:

cargo build --release

编译完成后,你会在target/release目录下找到生成的库文件。

  1. 在C或C++项目中调用Rust库。

创建一个新的C或C++项目,并在其中调用Rust库。首先,确保你已经安装了Rust和Cargo。

在C或C++项目的CMakeLists.txtMakefile中添加以下内容,以便链接到Rust库:

对于CMake:

find_library(RUST_LIB my_rust_lib PATHS /path/to/your/rust/library/target/release)
target_link_libraries(your_c_or_c++_project ${RUST_LIB})

对于Makefile:

RUST_LIB = /path/to/your/rust/library/target/release/libmy_rust_lib.so
your_c_or_c++_project: your_c_or_c++_project.o
    $(CC) -o your_c_or_c++_project your_c_or_c++_project.o -L/path/to/your/rust/library/target/release -lmy_rust_lib
  1. 在C或C++代码中调用Rust函数。

在你的C或C++项目中,包含Rust库的头文件(如果有的话),并调用Rust函数。例如:

#include <stdio.h>

// 声明Rust函数
extern void hello_from_rust();

int main() {
    printf("Calling Rust function...\n");
    hello_from_rust();
    return 0;
}
  1. 编译并运行C或C++项目。

编译并运行你的C或C++项目,你应该能看到Rust库中的函数被成功调用。

注意:如果你在编译过程中遇到链接错误,请确保你的Rust库和C或C++项目使用相同的ABI(例如,都使用C ABI)。在Rust库的lib.rs文件中,你可以使用#[no_mangle]extern "C"属性来确保使用C ABI。

0
看了该问题的人还看了