Swift conversion: ERROR - UnsafeMutablePointer

2019-07-25 09:52发布

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条回答
Summer. ? 凉城
2楼-- · 2019-07-25 10:17

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)
查看更多
登录 后发表回答