问题
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