我正在尝试将我的Swift 2代码转换为最新语法(Swift 3)。我收到以下错误:
无法为类型'UnsafeMutablePointer< CUnsignedChar>'调用初始值设定项使用类型'(UnsafeMutableRawPointer!)
的参数列表
Swift 2代码:
let rawData = UnsafeMutablePointer<CUnsignedChar>(calloc(height * width * 4, Int(sizeof(CUnsignedChar))))
有人可以帮我解决这个转换语法问题吗?
答案 0 :(得分:2)
calloc
返回一个“原始指针”(C中的Swift等价于void *
)。
您可以使用assumingMemoryBound
将其转换为类型指针:
let rawData = calloc(width * height, MemoryLayout<CUnsignedChar>.stride).assumingMemoryBound(to: CUnsignedChar.self)
或者使用allocate()
的{{1}}方法:
UnsafeMutablePointer