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

ε祈祈猫儿з 提交于 2019-12-05 09:01:13
kennytm

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