快速转换 : ERROR - UnsafeMutablePointer

标签 swift swift3 unsafe-pointers

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

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

swift 2 代码:

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

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

最佳答案

calloc 返回一个“原始指针”(Swift 相当于 C 中的 void *)。 您可以使用 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)

关于快速转换 : ERROR - UnsafeMutablePointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418647/

相关文章:

ios - 当用户使用 UITableView 的后退按钮滚动到最后选择的行时

swift - 如何访问 Swift 中 UnsafePointer 引用的结构的成员字段的 UnsafePointer?

swift - `UnsafePointer` 机制能否显示数据缓冲区中的向量数组以供在 SceneKit 中使用?

ios - 如何设置透明导航栏? iOS 11 快速 4 Xcode 9

Swift Scroll to UITextField via UiscrollView only acts first time 错误

Swift:通过可选属性将可选模型数组减少为单个 Bool

ios - Lazy 关键字对内存或性能有害吗?

swift - 动画 meteor 在 Swift 3 中从上到下移动

Swift addConstraint 导致 EXC_BAD_INSTRUCTION

ios - 使用 UnsafeMutablePointer 数组