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

爱⌒轻易说出口 提交于 2019-12-07 04:01:07

问题


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);
    }
}

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?


回答1:


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));
}

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);
}


来源:https://stackoverflow.com/questions/42523354/how-to-transfer-ownership-of-a-value-to-c-code-from-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!