Swift conversion: ERROR - UnsafeMutablePointer

北城以北 提交于 2020-02-25 04:45:09

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/41418647/swift-conversion-error-unsafemutablepointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!