快速转换:错误-UnsafeMutablePointer [英] Swift conversion: ERROR - UnsafeMutablePointer

查看:248
本文介绍了快速转换:错误-UnsafeMutablePointer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的Swift 2代码转换为最新的语法(Swift 3).我收到以下错误:

I am attempting to convert my Swift 2 code into the latest syntax(Swift 3). I am receiving the following error:

无法使用参数类型为((UnsafeMutableRawPointer!)!)的类型为'UnsafeMutablePointer< CUnsignedChar>'的初始化程序

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

Swift 2代码:

Swift 2 Code:

let rawData = UnsafeMutablePointer<CUnsignedChar>(calloc(height * width * 4, Int(sizeof(CUnsignedChar))))

有人可以帮助我解决此转换语法问题吗?

Can someone please help me resolve this conversion syntax issue?

推荐答案

calloc返回原始指针"(C中void *的Swift等效项). 您可以使用assumingMemoryBound将其转换为类型化的指针:

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)

或者使用UnsafeMutablePointerallocate()方法:

let rawData = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: width * height)
rawData.initialize(to: 0, count: width * height)
// ...

rawData.deinitialize()
rawData.deallocate(capacity: width * height)

这篇关于快速转换:错误-UnsafeMutablePointer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆