Last active
January 1, 2020 17:09
-
-
Save rothomp3/0a7b9fef4249a4f91fc6 to your computer and use it in GitHub Desktop.
Swift example of writing to memory buffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let bitmapBuffer = UnsafePointer<UInt8>.alloc(Int(height * width * 4)) | |
let pixelNumber = (x * 4) + (y * width * 4) | |
bitmapBuffer[pixelNumber + 3] = 255 // Alpha | |
bitmapBuffer[pixelNumber + 2] = redValue | |
bitmapBuffer[pixelNumber + 1] = greenValue | |
bitmapBuffer[pixelNumber + 0] = blueValue |
I think this is missing a dealloc
. Or put another way; I think this is leaking memory.
Using Swift 2 syntax I think this is a little bit better:
let bufferSize = Int(height * width * 4)
let bitmapBuffer = UnsafePointer<UInt8>.alloc(bufferSize)
defer { bitmapBuffer.dealloc(bufferSize) }
let pixelNumber = (x * 4) + (y * width * 4)
bitmapBuffer[pixelNumber + 3] = 255 // Alpha
bitmapBuffer[pixelNumber + 2] = redValue
bitmapBuffer[pixelNumber + 1] = greenValue
bitmapBuffer[pixelNumber + 0] = blueValue
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very helpful, thanks.