Swift 中最后一个数组元素的不安全指针

UnsafePointer to Last Array Element in Swift

我正在尝试在 Accelerate here 中使用 vDSP_conv 函数。 vDSP_conv 的参数之一是 "needs to point to the last vector element" 的 const float *__F。我不太熟悉在 Swift 中使用指针,所以我不知道如何创建指向 Swift 数组的最后一个数组元素的指针。

任何人都可以提供一些见解吗?

/** 编辑 **/

我尝试调用的函数说明: func vDSP_conv(_ __A: UnsafePointer<Float>, _ __IA: vDSP_Stride, _ __F: UnsafePointer<Float>, _ __IF: vDSP_Stride, _ __C: UnsafeMutablePointer<Float>, _ __IC: vDSP_Stride, _ __N: vDSP_Length, _ __P: vDSP_Length)

到目前为止,我有这段代码。我需要 y 指向数组中最后一个元素的指针,因为 conv 从数组的末尾开始并前进到前面

public func conv(x: [Float], y: [Float]) -> [Float] {
    var result = [Float](x)
    let inputLength:Int = x.count
    let outputLength:Int = inputLength + y.count - 1
    vDSP_conv(x, 1, y, 1, &result, 1, vDSP_Length(inputLength), vDSP_Length(outputLength))

    return result
}

withUnsafeBufferPointer() 给你一个指向数组的指针 连续存储,您可以从中计算指向的指针 最后一个数组元素:

func conv(x: [Float], y: [Float]) -> [Float] {
    var result = [Float](count: x.count - y.count + 1, repeatedValue: 0)

    y.withUnsafeBufferPointer { bufPtr in
        let pLast = bufPtr.baseAddress + y.count - 1
        vDSP_conv(x, 1, pLast, -1, &result, 1, vDSP_Length(result.count), vDSP_Length(y.count))
    }

    return result
}

(请注意,您对结果数组长度的计算不正确。)

示例:

print(conv([1, 2, 3], y: [4, 5, 6]))
// [ 28 ] = [ 1 * 6 + 2 * 5 + 3 * 6 ]

print(conv([1, 2, 3], y: [4, 5]))
// [ 13, 22 ] = [ 1 * 5 + 2 * 4, 2 * 5 + 3 * 4 ]