【问题标题】:UnsafePointer to Last Array Element in SwiftSwift 中指向最后一个数组元素的 UnsafePointer
【发布时间】:2016-02-05 02:15:49
【问题描述】:

我正在尝试在 Accelerate here 中使用 vDSP_conv 函数。 vDSP_conv 的参数之一是 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
}

【问题讨论】:

  • 你能展示你到目前为止所做的事情吗?
  • @CodeDifferent 请参阅帖子中的编辑。

标签: swift unsafe-pointers


【解决方案1】:

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 ]

【讨论】:

  • 感谢您的解决方案,也感谢您提出了结果数组的问题!
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多