【问题标题】:UnsafePointer no longer works in swift 3UnsafePointer 不再适用于 swift 3
【发布时间】:2016-10-03 03:47:26
【问题描述】:

我从 swift 2 转换为 swift 3 后,下面提到的行弹出错误

let value = UnsafePointer<UInt32>(array1).pointee

“init”不可用:使用“withMemoryRebound(to:capacity:_)”临时将内存视为另一种布局兼容类型。

在 swift2 中是这样的

let value = UnsafePointer<UInt32>(array1).memory

有人可以解释一下吗? 抱歉,我对 swift3 很陌生

修改后

let abc = UnsafePointer<UInt32>(array1).withMemoryRebound(to: <#T##T.Type#>, capacity: <#T##Int#>, <#T##body: (UnsafeMutablePointer<T>) throws -> Result##(UnsafeMutablePointer<T>) throws -> Result#>)

但仍然应该将什么值放入变量中?对不起,我已经搜索了但是太糟糕了我找不到解决方案

【问题讨论】:

  • Results from C functions that return nullable pointers must be explicitly unwrapped before accessing the pointee property (formerly memory) or subscript elements. Optional chaining syntax works well here, e.g. result?.pointee = sum. 可能会有所帮助...swift.org/migration-guide
  • 请展示你真正想要做什么。
  • array1是什么类型的?UnsafeRawPointer
  • @LinShiwei var array1 = [UInt8](count4: 重复 0)

标签: ios swift swift3


【解决方案1】:

你可以试试这个:

let rawPointer = UnsafeRawPointer(array1)
let pointer = rawPointer.assumingMemoryBound(to: UInt32.self)
let value = pointer.pointee

原始指针是用于访问非类型数据的指针。

assumingMemoryBound(to:) 可以从UnsafeRawPointer 转换为UnsafePointer&lt;T&gt;

参考:Swift 3.0 Unsafe World

【讨论】:

    【解决方案2】:

    如果arrayArray,最好使用withUnsafeBufferPointer

    array.withUnsafeBufferPointer { buffer in
        // do something with 'buffer'
        // (if you need an UnsafePointer rather than an UnsafeBufferPointer,
        // you can access that via the buffer's .baseAddress property)
    }
    

    确保不要让缓冲区指针从闭包中逃逸,因为它在闭包之外无效。

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多