I have the following code:
public struct HistogramData {
var red:[vImagePixelCount] = []
var green:[vImagePixelCount] = []
var blue: [vImagePixelCount] = []
var alpha: [vImagePixelCount] = []
}
And then I was accessing it as follows:
var data: HistogramData
...
let red:UnsafeMutablePointer<vImagePixelCount> = UnsafeMutablePointer(mutating: data.red)
let green:UnsafeMutablePointer<vImagePixelCount> = UnsafeMutablePointer(mutating: data.green)
let blue:UnsafeMutablePointer<vImagePixelCount> = UnsafeMutablePointer(mutating: data.blue)
The above lines were incorrect and XCode showed a warning of dangling pointers. So I modified the code as:
data.red.withUnsafeMutableBufferPointer { redPtr in
data.green.withUnsafeMutableBufferPointer { greenPtr in
data.blue.withUnsafeMutableBufferPointer { bluePtr in
let red = redPtr.baseAddress!
let green = greenPtr.baseAddress!
let blue = bluePtr.baseAddress!
for i in 0..<256 {
if red[i] > maxR {
maxR = red[i]
}
if green[i] > maxG {
maxG = green[i]
}
if blue[i] > maxB {
maxB = blue[i]
}
}
...
}
Even though the above code works, but I am not really sure we can use array indices on baseAddress in Swift. The right way may be to bind memory to certain size, but when the size of array is not specified, how does bindMemory work? How do I fix the above code if it is wrong (even though it may work, it may not be right)?
redPtr[i]
instead ofred[i]
.