我正在尝试使用 FFI 编写一些 Rust 代码,其中涉及 C 获取结构的所有权:
fn some_function() {
let c = SomeStruct::new();
unsafe {
c_function(&mut c);
}
}
I want c_function
取得所有权c
。在 C++ 中,这可以通过以下方式实现release
的方法unqiue_ptr
。 Rust 中有类似的东西吗?
The std::unique_ptr
C++中的类型对应于Box
在铁锈中,以及.release()
对应于Box::into_raw https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw.
let c = Box::new(SomeStruct::new());
unsafe {
c_function(Box::into_raw(c));
}
请注意,C 函数应将指针的所有权返回给 Rust 以销毁该结构。使用C释放内存是不正确的free
或 C++ 的delete
.
pub unsafe extern "C" fn delete_some_struct(ptr: *mut SomeStruct) {
// Convert the pointer back into a Box and drop the Box.
Box::from_raw(ptr);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)