[SOLVED] FFI: convert pointer to a multidimensional array



as function arguments, I have a pointer to a two-dimensional array and the array’s width and height:

fn foo(arr: *mut u64, width: usize, height: usize)

I’m looking for a way to cast it to some Rust structure (like vector), that can be indexed as arr[i][j] or arr[(i, j)]. I can cast it using std::slice::from_raw_parts_mut(arr, width*height), then wrap it with a structure and overload the std::ops::Index operator to take tuple (i, j) and return arr[i + j*width]. I just think that it’s quite a standard thing and there could be maybe some more elegant way (some built-in or library support) for doing it. Could you please point me to it if it exists?


OK, I have found a solution with the ndarray library.

let mut arr = ndarray::aview_mut1(
      unsafe{std::slice::from_raw_parts_mut(arr, width*height)}
).into_shape((width, height)).unwrap();