设计
-
Rust 中导出共享库,包含三个函数: -
student_new
,Rust 端分配内存并用默认值初始化,由 C 端填充和更新; -
student_alice
,Rust 端分配内存并初始化,由 C 端使用; -
student_free
,供 C 端用来释放结构体的内存 -
C 中定义 main
函数,连接 Rust 的共享库,并调用相关函数;
实现
.so
的共享库要在
Cargo.toml
中加上:
[lib]
crate-type = ["cdylib"]
// src/lib.rs
#[repr(C)]
#[derive(Debug)]
pub struct Student {
pub num: c_int,
pub total: c_int,
pub name: [c_char; 20],
pub scores: [c_float; 3],
}
// src/example_03.h
typedef struct Student
{
int num;
int total;
char name[20];
float scores[3];
} Student;
#[no_mangle]
pub extern "C" fn student_new() -> *mut Student {
let new_stu: Student = Default::default();
Box::into_raw(Box::new(new_stu))
}
#[no_mangle]
pub extern "C" fn student_alice() -> *mut Student {
let mut init_char_array: [c_char; 20] = [0; 20];
for (dest, src) in init_char_array.iter_mut().zip(b"Alice\0".iter()) {
*dest = *src as _;
}
let scores = [92.5, 87.5, 90.0];
let alice = Student {
num: 001,
total: 280,
name: init_char_array,
scores,
};
Box::into_raw(Box::new(alice))
}
#[no_mangle]
pub extern "C" fn student_free(p_stu: *mut Student) {
if !p_stu.is_null() {
unsafe {
println!("rust side print: {:?}", Box::from_raw(p_stu));
Box::from_raw(p_stu)
};
}
}
Student
中有个固定长度的
c_char
数组。如何在 Rust 中初始化它并为其赋值呢?
c_char
表示 C 中的字符
char
,但 C 的
char
类型(表示一个整数)彻底不一样于 Rust 的
char
类型(表示一个 Unicode 标量值),因此在 Rust 中的
c_char
其实是
i8/u8
。
let mut init_char_array: [c_char; 20] = [0; 20];
for (dest, src) in init_char_array.iter_mut().zip(b"Alice\0".iter()) {
*dest = *src as _;
}
zip
函数一次遍历两个数组,并完成赋值。
// csrc/main.c
int main(void) {
Student *c_ptr = student_alice();
printf("Student Num: %d\t Total: %d\t Name: %s\t\n", c_ptr->num, c_ptr->total, c_ptr->name);
student_free(c_ptr);
Student *stu = student_new();
printf("Before fill data: Student Num: %d\t Total: %d\t Name: %s\t Scores: %.1f\t%.1f\t%.1f\n",
stu->num, stu->total, stu->name,
stu->scores[0], stu->scores[1], stu->scores[2]);
stu->num = 2;
stu->total = 212;
strcpy(stu->name, "Bob");
stu->scores[0] = 60.6;
stu->scores[1] = 70.7;
stu->scores[2] = 80.8;
printf("After fill data: Student Num: %d\t Total: %d\t Name: %s\t Scores: %.1f\t%.1f\t%.1f\n",
stu->num, stu->total, stu->name,
stu->scores[0], stu->scores[1], stu->scores[2]);
student_free(stu);
return 0;
}
Makefile
,编译并运行。结果以下:
➜ example_03 git:(master) ✗ make
/data/cargo/bin/cargo clean
rm -f ./csrc/main
/data/cargo/bin/cargo build --release
Compiling example_03 v0.1.0 (/data/github/lester/rust-practice/ffi/example_03)
Finished release [optimized] target(s) in 0.39s
/usr/bin/gcc -o ./csrc/main ./csrc/main.c -Isrc -L. -l:target/release/libexample_03.so
./csrc/main
Student Num: 1 Total: 280 Name: Alice
rust side print: Student { num: 1, total: 280, name: [65, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], scores: [92.5, 87.5, 90.0] }
Before fill data: Student Num: 0 Total: 0 Name: Scores: 0.0 0.0 0.0
After fill data: Student Num: 2 Total: 212 Name: Bob Scores: 60.6 70.7 80.8
rust side print: Student { num: 2, total: 212, name: [66, 111, 98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], scores: [60.6, 70.7, 80.8] }
student_free
函数来释放结构体的内存。
结论
本文分享自微信公众号 - Rust语言中文社区(rust-china)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。git