知识卡片

结构图卡 · 1441.b.2

原生资源包装统一取得与释放

理解等级:中级

FfiWrapper可在new检查分配结果,Drop调用对应free函数,将资源责任集中到一个拥有者。安全方法还需证明指针对齐、指向初始化有效值、存活且符合别名规则;仅检查非空不能支撑&mut引用。释放必须唯一且使用正确分配器,不能依赖调用者碰巧不重复释放。

结构图:

classDiagram
class FfiStruct {
  +u8 byte
  +u32 integer
}
class FfiWrapper {
  inner: *mut FfiStruct
  +new(val: u32) Result~Self_Error~
  +set_byte(&mut self, b: u8)
  +drop(&mut self)
}
FfiWrapper --> FfiStruct : 拥有C分配资源并匹配释放

箭头表示资源拥有责任,非Rust字段直接内嵌;drop属于Drop实现,C分配释放函数并非类型。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 6. Beyond Standard Rust Lifetimes · 查看原书依据

      FfiWrapper { // Invariant: inner is non-NULL. inner: *mut FfiStruct, } and the Drop implementation returns that memory to the C library to avoid the potential for leaks: /// Manual implementation of [`Drop`], which ensures that memory allocated /// by the C library is freed by it. impl Drop for FfiWrapper { fn drop(&mut self) { // Safety: `inner` is non-NULL

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第6章《Lifetimes》(spine10;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch06.html;u179-ch06-014)。 - 结论依据:原文在“FfiWrapper”附近的定义、例子或代码支撑本卡核心说明:FfiWrapper可在new检查分配结果,Drop调用对应free函数,将资源责任集中到一个拥有者。边界按已读前提解释;示例未执行。 - 原始内容:FfiWrapper { // Invariant: inner is non-NULL. inner: *mut FfiStruct, } and the Drop implementation returns that memory to the C library to avoid the potential for leaks: /// Manual implementation of [`Drop`], which ensures that memory allocated /// by the C library is freed by it. impl Drop for FfiWrapper { fn drop(&mut self) { // Safety: `inner` is non-NULL