Rust在Ubuntu上怎样与C/C++交互

作者:袖梨 2026-06-20

在Ubuntu上,Rust可以通过外部函数接口(FFI)与C/C++交互。这允许Rust代码调用C库中的函数,反之亦然。以下是在Ubuntu上实现Rust与C/C++交互的基本步骤:

Rust在Ubuntu上如何与C/C++交互

1. 安装Rust

首先,确保你已经安装了Rust。如果没有,可以通过以下命令安装:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/env

2. 创建Rust项目

创建一个新的Rust库项目:

cargo new --lib my_rust_libcd my_rust_lib

3. 配置Cargo.toml

编辑Cargo.toml文件,添加extern crate声明和[lib]部分的crate-type设置为cdylib,以便生成动态链接库(.so文件):

[lib]name = "my_rust_lib"crate-type = ["cdylib"][dependencies]

4. 编写Rust代码

src/lib.rs中编写Rust代码,并使用extern "C"块声明要暴露给C的函数:

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

5. 编译Rust代码

使用以下命令编译Rust代码:

cargo build --release

编译完成后,在target/release目录下会生成一个动态链接库文件,例如libmy_rust_lib.so

6. 创建C/C++项目

创建一个新的C/C++项目,并确保它能够链接到Rust生成的动态链接库。

C示例

创建一个名为main.c的文件:

#include <stdio.h>// 声明Rust函数void rust_function();int main() {printf("Calling Rust function...n");rust_function();return 0;}

编译C代码并链接Rust库:

gcc -o my_c_program main.c -L/path/to/rust/library -lmy_rust_lib -lpthread -ldl

确保将/path/to/rust/library替换为实际的Rust库路径。

C++示例

创建一个名为main.cpp的文件:

#include <iostream>// 声明Rust函数extern "C" void rust_function();int main() {std::cout << "Calling Rust function..." << std::endl;rust_function();return 0;}

编译C++代码并链接Rust库:

g++ -o my_cpp_program main.cpp -L/path/to/rust/library -lmy_rust_lib -lpthread -ldl

7. 运行程序

运行编译后的C或C++程序:

./my_c_program# 或者./my_cpp_program

你应该会看到输出:

Calling Rust function...Hello from Rust!

注意事项

  • 确保Rust和C/C++编译器都支持相同的ABI(应用程序二进制接口)。
  • 使用extern "C"确保Rust函数使用C ABI,这样C/C++代码才能正确调用它们。
  • 处理好内存管理和所有权问题,避免在Rust和C/C++之间传递不安全的数据。

通过以上步骤,你可以在Ubuntu上实现Rust与C/C++的交互。

相关文章

精彩推荐