< 返回版块

洋芋 发表于 2020-08-26 23:41

Tags:rust, ffi, c, struct, repr

本节主要介绍 Rust 导出共享库时,如何通过指针在 Rust 和 C 之间传递结构体。上一节的示例是结构体的内存在 C 端分配,本节介绍内存在 Rust 这边分配,由 C 填充和使用。

设计

本节的示例:

  • Rust 中导出共享库,包含三个函数:
    • student_new,Rust 端分配内存并用默认值初始化,由 C 端填充和更新;
    • student_alice,Rust 端分配内存并初始化,由 C 端使用;
    • student_free,供 C 端用来释放结构体的内存
  • C 中定义main函数,链接 Rust 的共享库,并调用相关函数;

实现

工程的初始化类似之前的导出共享库示例,导出.so的共享库要在Cargo.toml中加上:

[lib]
crate-type = ["cdylib"]

下面我们直接看示例的代码。

首先,在 Rust 端和 C 头文件中定义声明要传递的结构体。

// 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;

其次在 Rust 端实现我们设计的三个函数。

#[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 中初始化它并为其赋值呢?

我们知道 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函数一次遍历两个数组,并完成赋值。

接下来我们在 C 的头文件中声明这三个函数,并看看 C 端的调用代码。

// 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] }

我们可以看出,Rust 端分配内存并初始化的结构体,在 C 端可以被完美地使用和更新,要注意的是在调用后,需要调用student_free函数来释放结构体的内存。

结论

本文通过设计一个示例,演示了 Rust 导出共享库时,提供内存分配和释放的函数,通过指针传递结构体,并在 C 端完美实现使用和更新结构体。

本章示例的所有代码:https://github.com/lesterli/rust-practice/tree/master/ffi/example_03。

评论区

写评论

还没有评论

1 共 0 条评论, 1 页