如何将值的所有权从 Rust 转移到 C 代码?

How to transfer ownership of a value to C code from Rust?

我正在尝试使用 FFI 编写一些 Rust 代码,其中涉及 C 获取结构的所有权:

fn some_function() {
    let c = SomeStruct::new();
    unsafe {
        c_function(&mut c);
    }
}

我希望 c_function 获得 c 的所有权。在 C++ 中,这可以通过 unqiue_ptrrelease 方法来实现。 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 函数应该 return 指向 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);
}