Vec pointer to Swift Array invalid values

Hi I'm a bit confused here so i have a f32 pointer (a matrix ... a Vec slice) along with the length to pass to swift funny thing after creating an Array in swift the first 3 values are always wrong the other 3 are fine
// native_get_matrix
let mut data = data.as_mut_slice();
CanvasArray {
array: data.as_mut_ptr() as *mut c_void,
length: data.len(),

let matrixValues = native_get_matrix(matrix)
        let values = Array(UnsafeMutableBufferPointer(start:  matrixValues.array.assumingMemoryBound(to: Float.self), count: matrixValues.length))

[src/common/] &matrix = [
[6.1735027e+18, 1.586e-42, 2.863e-42, 1.0, 0.0, 0.0]

Thanks in advance :slight_smile:

Seeing that you are calling &mut self methods on the Vec, I have a suspicion that your data is not living for long enough.

  1. You construct your Vec<f32>
  2. You construct your CanvasArray with pointer and length into the data behind that Vec
  3. The function ends, and possibly the Vec is dropped?
  4. The memory in the Vec gets overwritten with something else
  5. Swift reads junk data

I'm reading between the lines here - I could be completely off the mark. Really we need see all of native_get_matrix and understand the source of data. If that is the problem, you will probably need to put it onto the heap temporarily (see Box::into_raw) or provide a buffer from Swift for Rust to fill in.

1 Like

Thanks putting it on the heap helped :dancer:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.