知识卡片
转移堆指针必须配套唯一收回
把局部Box内容地址返回C仍会在Box析构后失效。Box::into_raw转交堆对象责任,后续可由匹配的Rust入口用from_raw收回并析构。from_raw要求正确来源、布局与唯一拥有,非空检查不够;同一指针重复收回、外部分配器混用都会破坏安全。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 6. Beyond Standard Rust Invoking Rust from C · 查看原书依据
Box::into_raw, which abnegates responsibility for the heap object, effectively “forgetting” about it: #[no_mangle] pub extern "C" fn new_struct_raw(v: u32) -> *mut FfiStruct { let s = FfiStruct::new(v); // create `FfiStruct` on stack let b = Box::new(s); // move `FfiStruct` to heap // Consume the `Box` and take responsibility for the heap memory. Box::into_r
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第6章《Invoking Rust from C》(spine10;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch06.html;u180-ch06-016)。
- 结论依据:原文在“Box::into_raw”附近的定义、例子或代码支撑本卡核心说明:把局部Box内容地址返回C仍会在Box析构后失效。边界按已读前提解释;示例未执行。
- 原始内容:Box::into_raw, which abnegates responsibility for the heap object, effectively “forgetting” about it: #[no_mangle] pub extern "C" fn new_struct_raw(v: u32) -> *mut FfiStruct { let s = FfiStruct::new(v); // create `FfiStruct` on stack let b = Box::new(s); // move `FfiStruct` to heap // Consume the `Box` and take responsibility for the heap memory. Box::into_r