Skip to content

Instantly share code, notes, and snippets.

@chockenberry
Last active October 21, 2021 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chockenberry/30608eae03f63750363fc1470991f166 to your computer and use it in GitHub Desktop.
Save chockenberry/30608eae03f63750363fc1470991f166 to your computer and use it in GitHub Desktop.
vImage_Buffer Unsafe Mutable Pointers
let srcRowBytes = workingBuffer.buffer.rowBytes
let srcData: UnsafeMutablePointer<Pixel_8> = workingBuffer.buffer.data!.assumingMemoryBound(to: Pixel_8.self)
let srcIndex = y * srcRowBytes + x * workingBuffer.bytesPerPixel
var srcPointer = srcData[srcIndex]
withUnsafeMutablePointer(to: &srcPointer) { srcPointer in
// srcPointer is (UnsafeMutablePointer<Pixel_8>)
var srcBuffer = vImage_Buffer(data: srcPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: srcRowBytes)
...
var error = kvImageNoError
// EXC_BAD_ACCESS because srcPointer is not srcData + srcIndex
error = vImageConvert_AnyToAny(converter, &srcBuffer, &dstBuffer, nil, vImage_Flags(kvImagePrintDiagnosticsToConsole))
}
@chockenberry
Copy link
Author

chockenberry commented Oct 20, 2021

Previously, this code was:

var srcBuffer = vImage_Buffer(data: &srcData[srcIndex], height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: srcRowBytes)

But there's an inout warning about the &srcData temporary pointer:

Inout expression creates a temporary pointer, but argument 'data' should be a pointer that outlives the call to 'init(data:height:width:rowBytes:)'

@chockenberry
Copy link
Author

For anyone who stumbles across this gist with search, the fix is to create the vImage_Buffer like this:

var srcBuffer = vImage_Buffer(data: srcData.advanced(by: srcIndex), height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: srcRowBytes)

For more help, check out these links:

Apple documentation: https://developer.apple.com/documentation/accelerate/applying_vimage_operations_to_regions_of_interest
Twitter thread: https://twitter.com/chockenberry/status/1450885687369101313

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment