Rust与C接口交互的核心方法
Rust与C的交互主要通过extern关键字和#[no_mangle]属性实现。extern块用于定义或声明外部函数接口(FFI),而#[no_mangle]确保函数名在编译后不被混淆,便于C代码调用。
#[no_mangle]
pub extern "C" fn rust_add(a: i32, b: i32) -> i32 {
a + b
}
对应的C头文件声明:
int rust_add(int a, int b);
数据类型的兼容性处理
基础类型如i32、f64等可直接映射到C的int、double。复合类型需使用#[repr(C)]强制内存布局与C兼容:
#[repr(C)]
pub struct Point {
x: i32,
y: i32,
}
C端对应结构体:
typedef struct {
int x;
int y;
} Point;
所有权与生命周期的管理
Rust到C传递指针时需明确所有权。使用Box::into_raw转换所有权到C端,返回时用Box::from_raw回收:
#[no_mangle]
pub extern "C" fn create_point(x: i32, y: i32) -> *mut Point {
Box::into_raw(Box::new(Point { x, y }))
}
#[no_mangle]
pub extern "C" fn free_point(p: *mut Point) {
unsafe { Box::from_raw(p) };
}
错误处理机制
通过返回错误码和输出参数传递错误信息:
#[repr(C)]
pub enum ErrorCode {
Ok,
InvalidInput,
}
#[no_mangle]
pub extern "C" fn parse_input(input: *const c_char, output: *mut i32) -> ErrorCode {
unsafe {
if input.is_null() {
return ErrorCode::InvalidInput;
111

被折叠的 条评论
为什么被折叠?



