0

I am new to Rust. I want to use Rust to speed up an existing Python program I made. I know that the data type is f64 and I know the array length. I want to return an array and then free it from memory.

What's the correct way to free a Vec<f64> pointer from memory?

This works:

// Source: https://www.reddit.com/r/rust/comments/aca3do/comment/ed6z5n3/?utm_source=share&utm_medium=web2x&context=3
#[no_mangle]
pub unsafe extern "C" fn arr(buffer: *mut f64, length: u32)
{
    let v: Vec<f64> = vec![1.0; 10];
    std::slice::from_raw_parts_mut(buffer, length as usize).copy_from_slice(&v);
}

This (apparently) does not:

// Source: https://www.reddit.com/r/rust/comments/aca3do/comment/ed6z5n3/?utm_source=share&utm_medium=web2x&context=3
#[no_mangle]
pub unsafe extern "C" fn free_arr(pointer: *mut f64, length: u32)
{
    let layout = Layout::array::<f64>(length as usize).unwrap();
    dealloc(pointer as *mut u8, layout);
}

In Python:

from ctypes import CDLL, POINTER, c_double, cast

lib = CDLL("my_dll.dll")
length = 10
arr = (c_double * length)()
pointer = cast(arr, POINTER(c_double))
lib.arr(pointer, length)
print(list(arr))
lib.free_arr(pointer, length)
print("done!")

Expected result:

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
done!

Actual result:

[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

Process finished with exit code -1073740940 (0xC0000374)
  • 1
    The method `arr` does not really provide a `Vec` through FFI, it copies some numbers onto an existing memory buffer allocated by the caller. That Python code might not be doing the allocation either. Best to follow [this answer](https://stackoverflow.com/a/39270881) instead. – E_net4 Mar 03 '23 at 17:07

0 Answers0