Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 854
kkspeed Avatar asked Mar 01 '17 04:03

kkspeed


1 Answers

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);
}
like image 114
kennytm Avatar answered Oct 15 '22 20:10

kennytm