Vitya Shurapov Vitya Shurapov - 1 year ago 115
iOS Question

UnsafeRawPointer Migration

I've found one nice project with 360 player on GitHub.

When I converted it to the last Swift3 syntax I've got this error:

"Cannot invoke initializer for type 'UnsafeMutablePointer' with an argument list of type '(UnsafeMutableRawPointer!)"

"Overloads for 'UnsafeMutablePointer' exist with these partially matching parameter lists: (RawPointer), (OpaquePointer), (OpaquePointer?), (UnsafeMutablePointer), (UnsafeMutablePointer?)"

I also get this article with how to migrate but it's too hard to me to fix it by myself.

It happens in this block of code:

// MARK: - Texture

func loadTexture(_ image: UIImage?)
guard let image = image else

let width = image.cgImage?.width
let height = image.cgImage?.height

// there is an error!
let imageData = UnsafeMutablePointer(calloc(Int(width! * height! * 4), sizeof(GLubyte)))

let imageColorSpace = image.cgImage?.colorSpace
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let gc = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: imageColorSpace, bitmapInfo: bitmapInfo.rawValue)
gc.draw(image.cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)))

self.updateTexture(CGSize(width: width, height: height), imageData: imageData)

Answer Source

This code:

calloc(Int(width! * height! * 4), sizeof(GLubyte))

returns a UnsafeMutableRawPointer. UnsafeMutablePointer does not offer a initializer with argument of this type.

Instead of using calloc:

 let imageData = UnsafeMutablePointer(calloc(Int(width! * height! * 4), sizeof(GLubyte)))

create your buffer manually:

let numPixel = Int(width! * height! * 4)
let buffer = [GLubyte](repeating: 0, count: numPixel)
let imageData = UnsafeMutablePointer<GLubyte>(mutating: buffer) as UnsafeMutablePointer<GLubyte>?

(not tested)