简体   繁体   中英

UnsafeRawPointer Migration

I've found one nice project with 360 player on GitHub. https://github.com/iosdevzone/360Video

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!) " and

" 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. https://swift.org/migration-guide/se-0107-migrate.html

It happens in this block of code:

// MARK: - Texture

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

    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)
    free(imageData)
}

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 array like this:

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

(not tested)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM