使用 UnsafeMutablePointer 数组

Working with UnsafeMutablePointer array

我正在尝试使用 Brad Larson 出色的 GPUImage 框架,但我正在努力处理 GPUImageHarrisCornerDetectionFilter.

返回的 cornerArray

角在 UnsafeMutablePointer 中作为 GLFloat 的数组返回 - 我想将其转换为 CGPoint

的数组

我试过为内存分配space

var cornerPointer = UnsafeMutablePointer<GLfloat>.alloc(Int(cornersDetected) * 2)

但数据似乎没有任何意义 - 零或 1E-32

我找到了完美的答案 how to loop through elements of array of <UnsafeMutablePointer> in Swift 并尝试了

filter.cornersDetectedBlock = {(cornerArray:UnsafeMutablePointer<GLfloat>, cornersDetected:UInt, frameTime:CMTime) in
        crosshairGenerator.renderCrosshairsFromArray(cornerArray, count:cornersDetected, frameTime:frameTime)

    for floatData in UnsafeBufferPointer(start: cornerArray, count: cornersDetected)
    {
        println("\(floatData)")
    }

但编译器不喜欢 UnsafeBufferPointer - 所以我将其更改为 UnsafeMutablePointer,但它不喜欢参数列表。

我敢肯定这既好又简单,而且听起来像其他人必须不得不做的事情 - 那么解决方案是什么?

试试这个:

     var cornerPointer = UnsafeMutablePointer<GLfloat>.alloc(Int(cornersDetected) * 2)

    filter.cornersDetectedBlock = {(cornerArray:UnsafeMutablePointer<GLfloat>, cornersDetected:UInt, frameTime:CMTime) in
        crosshairGenerator.renderCrosshairsFromArray(cornerArray, count:cornersDetected, frameTime:frameTime)

    for i in 0...cornersDetected
    {
        print("\(cornerPointer[i])")
    }

我找到了解决方案 - 而且很简单。答案在这里 https://gist.github.com/kirsteins/6d6e96380db677169831

var dataArray = Array(UnsafeBufferPointer(start: cornerArray, count: Int(cornersDetected) * 2))

从 C 翻译而来的 UnsafeMutablePointer<GLfloat> 类型可以通过下标访问其元素,就像普通数组一样。为了实现将这些转换为 CGPoints 的目标,我将使用以下代码:

filter.cornersDetectedBlock = { (cornerArray:UnsafeMutablePointer<GLfloat>, cornersDetected:UInt, frameTime:CMTime) in
    var points = [CGPoint]()
    for index in 0..<Int(cornersDetected) {
       points.append(CGPoint(x:CGFloat(cornerArray[index * 2]), y:CGFloat(cornerArray[(index * 2) + 1])))
    }
    // Do something with these points
}

内存支持 cornerArray 在回调被触发之前立即分配,并在它之后立即释放。除非您像我在上面所做的那样在块的中间复制这些值,否则恐怕您会让自己面临一些讨厌的错误。无论如何,此时转换为正确的格式也更​​容易。