如何将值的所有权从Rust转移到C代码? [英] How to transfer ownership of a value to C code from Rust?
问题描述
我正在尝试使用FFI编写一些Rust代码,其中涉及C取得结构的所有权:
I'm trying to write some Rust code with FFI that involves C taking ownership of a struct:
fn some_function() {
let c = SomeStruct::new();
unsafe {
c_function(&mut c);
}
}
我希望c_function
拥有c
的所有权.在C ++中,这可以通过unqiue_ptr
的release
方法来实现. Rust中有类似的东西吗?
I want c_function
to take ownership of c
. In C++, this could be achieved by the release
method of unqiue_ptr
. Is there something similar in Rust?
推荐答案
C ++中的std::unique_ptr
类型对应于Rust中的Box
和.release()
The std::unique_ptr
type in C++ corresponds to Box
in Rust, and .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
释放内存是不正确的.
Note that the C function should return the ownership of the pointer to Rust to destroy the structure. It is incorrect to free the memory using C's free
or C++'s 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转移到C代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!