如何将值的所有权从Rust转移到C代码? [英] How to transfer ownership of a value to C code from Rust?

查看:335
本文介绍了如何将值的所有权从Rust转移到C代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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_ptrrelease方法来实现. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆