我正在尝试使用 FFI 编写一些 Rust 代码,其中涉及 C 获取结构的所有权:
fn some_function() {
let c = SomeStruct::new();
unsafe {
c_function(&mut c);
}
}
我希望 c_function
获得 c
的所有权。在 C++ 中,这可以通过 unqiue_ptr
的 release
方法来实现。 Rust 中有类似的东西吗?
最佳答案
C++中的std::unique_ptr
类型对应Rust中的Box
,.release()
corresponds to Box::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);
}
关于rust - 如何将值的所有权从 Rust 转移到 C 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42523354/