如何从Swift 3中的不透明指针创建一个类型化指针?

时间:2016-09-16 20:39:12

标签: swift pointers swift3 unsafemutablepointer

转换为Swift 3我收到编译器错误:

  

无法使用类型'UnsafeMutablePointer'调用初始值设定项   类型'(UnsafeMutableRawPointer?)'

的参数列表

尝试从不透明指针创建类型指针时:

let imageRef = myUIImage.cgImage!
let context = CGContext(...)!
let rect = CGRect(...)
context.draw(imageref, in: rect)

var data = context.data
var dataType = UnsafeMutablePointer<UInt8>(data) //Throws the error

为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

content.data返回UnsafeMutableRawPointer。它有bindMemoryassumingMemoryBound方法转换为类型指针:

let dataType = data.bindMemory(to: UInt8.self, capacity: n) // UnsafeMutablePointer<UInt8>

我没有机会测试n是什么,但我怀疑它会是这样的:

n = width * height * bitsPerPixel / 8