Search code examples
rustffiownership

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?


Solution

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