I would like to convert a 2D Numpy array in Python to a Rust vector. Specifically, the second dimension of the array is known. That is, the array is in shape [VARIABLE, 1024] (with type double) I would like to know how I could convert it to a Rust vector. Specifically, Vec<[f64; 1024]>
I know that I should use rust-numpy to do this And the first step should be converting it into PyReadonlyArray2 But I'm not sure what should I do next?
ndarraydoes not support constant dimensions, so you won't find support for converting into arrays (nalgebradoes support them, but it looks like it doesn't have support for converting toVec). So the first step will be to convert toVec<f64>, and then transmute that intoVec<[f64; 1024]>(this can be done without unsafe code with a crate likebytemuck).The first step can also be quite involved if we want to do it efficiently. It will be good if we can just allocate directly and copy the contents using
memcpy(); however, we can only do that if the array is contiguous (i.e. not a view that is not contiguous), and it is in C layout, i.e. row-major layout, and not Fortran layout (column-major).All in all:
Edit: Turns out this can be done with
ndarraymethods without much trouble, and this is also faster in case of non-contiguous layout: