設計
-
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