The article Controlling vDSP Operations with Stride says in the “Use a Negative Stride” section:
To use a negative stride, create a pointer to the last element in the array by initializing an UnsafePointer that's advanced by the number of elements less one.
and gives the following example:
let a: [Float] = [10, 20, 30, 40, 50, 60, 70, 80]
let b: [Float] = [ 1, 2, 3, 4, 5, 6, 7, 8]
let n = vDSP_Length(a.count)
var c = [Float](repeating: .nan, count: a.count)
let strideA = vDSP_Stride(-1)
let strideB = vDSP_Stride(1)
let strideC = vDSP_Stride(1)
vDSP_vadd(UnsafePointer(a).advanced(by: a.count - 1), strideA,
b, strideB, &c, strideC, n)
I wonder if/why this use of UnsafePointer(a)
is correct. The documentation states that
... You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior.
I thought that passing a
to UnsafePointer(_ other: UnsafePointer<Float>)
creates a temporary pointer to the element storage, and that might be invalid after the init method returns.
Would it better/correct to use a.withUnsafeBufferPointer(...)
instead?