1

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?

0

1 Answer 1

2

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) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.