swift - 如何为 Swift 3 更新 UnsafePointer 的数据声明?

标签 swift swift3 unsafe-pointers

对于此声明,我收到以下错误:

 let data = Data(bytes: UnsafePointer<UInt8>(cubeData), count: cubeData.count * MemoryLayout<Float>.size)

cubeData 定义为:var cubeData = [Float](repeating: 0, count: size * size * size * 4)

错误:

 'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

我该如何解决这个问题?

谢谢!

最佳答案

你可以使用 Array.withUnsafeBufferPointer获取缓冲区指针(即指向具有其长度的数组的指针)。然后使用 Data.init(buffer:)从缓冲区指针启动数据。

let cubeData: [Float] = [1.1, 2.2, 3.3, 4.4]

let b = cubeData.withUnsafeBufferPointer { Data(buffer: $0) }

print(b as NSData)
// <cdcc8c3f cdcc0c40 33335340 cdcc8c40>

关于swift - 如何为 Swift 3 更新 UnsafePointer 的数据声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40949075/

相关文章:

swift - Storyboard 未链接到 ViewController.swift Xcode 中的 @IBAction/Outlet

ios - iAd 横幅占用不必要的空间

ios - 线程与加载飞溅同步

swift - Alamofire 4 - 无法调用非函数类型 HTTPURLResponse 的值

ios - 如何通过点击取消按钮显示两个 ViewController 之一?

java - 在 Java 中使用 Unsafe 写/读内存

arrays - Swift:2 个类似错误:无法使用 'x' 类型的参数列表调用 '(([xx]) -> ())'

ios - 在委托(delegate)方法中使用默认行为对 UITextField 进行子类化的设计方法

null - Swift:gettimeofday 和不安全指针