Rust 与 C 语言交互主要通过 FFI(Foreign Function Interface)实现。FFI 允许 Rust 代码调用 C 语言函数,反之亦然。以下是一些基本步骤和注意事项:
首先,你需要一个 C 库。假设你有一个简单的 C 函数:
// my_c_library.h
#ifndef MY_C_LIBRARY_H
#define MY_C_LIBRARY_H
#ifdef __cplusplus
extern "C" {
#endif
void my_c_function();
#ifdef __cplusplus
}
#endif
#endif // MY_C_LIBRARY_H
// my_c_library.c
#include "my_c_library.h"
#include <stdio.h>
void my_c_function() {
printf("Hello from C!\n");
}
编译这个库:
gcc -c my_c_library.c -o my_c_library.o
ar rcs libmyclib.a my_c_library.o
在 Rust 中,你需要使用 extern 块来声明外部函数,并使用 unsafe 块来调用它们。
// main.rs
extern crate libc;
use std::os::raw::{c_void};
#[link(name = "myclib", kind = "static")]
extern "C" {
fn my_c_function();
}
fn main() {
unsafe {
my_c_function();
}
}
你需要确保 Rust 编译器知道 C 库的位置和名称。可以通过在 Cargo.toml 中添加 [dependencies] 和 [build-dependencies] 来实现。
[dependencies]
libc = "0.2"
[build-dependencies]
cc = "1.0"
创建一个 build.rs 文件来编译 C 库:
// build.rs
extern crate cc;
fn main() {
cc::Build::new()
.file("my_c_library.c")
.compile("myclib");
}
确保 C 库文件(例如 libmyclib.a)在 Rust 程序的运行路径中,或者在系统库路径中。然后运行 Rust 程序:
cargo run
通过以上步骤,你可以在 Linux 上实现 Rust 与 C 语言的交互。