如何获得UnsafeMutableBufferPointer的一部分作为一个新的UnsafeMutableBufferPointer

问题描述:

我在玩Swift中的图像处理。使用this代码访问图像像素。如何获得UnsafeMutableBufferPointer的一部分作为一个新的UnsafeMutableBufferPointer

图像像素指向UnsafeMutableBufferPointer

所有像素数据的一个列表,每个像素位置需要被计算:

let index = y * rgba.width + x 
let pixel = pixels[index] 

我想添加一个subscript因此对于获得

public subscript(index: Int) -> [Pixel] { 
    get { 
     var column = [Pixel]() 
     for i in 0..<height { 
      column.append(pixels[index*height + i]) 
     } 

     return column 
    } 
} 

那么,有一种方法返回指向右列的UnsafeMutableBufferPointer?而不是一个数组?

我试图避免更多的内存分配。

感谢

+0

除非我弄错了,像素数据被安排在*行*不列。换句话说,列的像素不在连续的存储器中。 –

+0

另请注意,UnsafeMutableBufferPointer是“非拥有”的,只有存在基础元素存储时才有效。 –

+1

RGBA代码泄漏内存:像素数据的分配内存永远不会释放。 –

就像那个?:

public subscript(rowIndex: Int) -> UnsafePointer<Pixel> { 
    return pixels.baseAddress!.advanced(by: rowIndex * height) 
} 
public subscript(rowIndex: Int) -> UnsafeBufferPointer<Pixel> { 
    return UnsafeBufferPointer(start: self[rowIndex], count: height) 
} 
+0

这在代码中有编译错误。 – ilan

+0

它只是告诉你如何去做,你需要将它集成到你的特定设置中。 – hnh