I am attempting to convert my Swift 2 code into the latest syntax(Swift 3). I am receiving the following error:
Cannot invoke initializer for type 'UnsafeMutablePointer<CUnsignedChar>' with an argument list of type '(UnsafeMutableRawPointer!)
Swift 2 Code:
let rawData = UnsafeMutablePointer<CUnsignedChar>(calloc(height * width * 4, Int(sizeof(CUnsignedChar))))
Can someone please help me resolve this conversion syntax issue?
calloc
returns a "raw pointer" (the Swift equivalent of void *
in C).
You can convert it to a typed pointer with assumingMemoryBound
:
let rawData = calloc(width * height, MemoryLayout<CUnsignedChar>.stride).assumingMemoryBound(to: CUnsignedChar.self)
Alternatively use the allocate()
method of UnsafeMutablePointer
:
let rawData = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: width * height)
rawData.initialize(to: 0, count: width * height)
// ...
rawData.deinitialize()
rawData.deallocate(capacity: width * height)