我正在从Rust调用一个C函数,它将一个空指针作为一个参数,然后分配一些内存来指向它.
什么是有效(即避免不必要的副本)和安全(即避免内存泄漏或段错误)的正确方法是将数据从C指针转换为Vec?
我有类似的东西:
extern "C" {
// C function that allocates an array of floats
fn allocate_data(data_ptr: *mut *const f32, data_len: *mut i32);
}
fn get_vec() -> Vec<f32> {
// C will set this to length of array it allocates
let mut data_len: i32 = 0;
// C will point this at the array it allocates
let mut data_ptr: *const f32 = std::ptr::null_mut();
unsafe { allocate_data(&mut data_ptr, &mut data_len) };
let data_slice = unsafe { slice::from_raw_parts(data_ptr as *const …Run Code Online (Sandbox Code Playgroud)