Swift 3不安全指针

时间:2016-11-16 16:48:19

标签: ios swift2 swift3

我正在从Swift 2迁移到Swift 3,而且我一度陷入困境。

Swift 2

let arr = UnsafePointer<UInt32>(UnsafePointer<UInt8>(buf).advanced(by: off))
let msk = arr[0].bigEndian & 0x7fffffff

我在第一行说错误

  

'init'不可用:使用'withMemoryRebound(to:capacity:_)'来   暂时将内存视为另一种与布局兼容的类型。

我尝试使用withMemoryoRebound方法,但我不确定参数。 根据{{​​3}},UnsafePointer<>已被UnsafeRawPointer取代。所以我改变了我的代码,如下所示

let arr = UnsafeRawPointer(UnsafePointer<UInt8>(buf).advanced(by: off))
let msk = arr[0].bigEndian & 0x7fffffff

但是在第二行它说

  

类型'UnsafeRawPointer'没有下标成员

如何成功将其转换为Swift 3?

2 个答案:

答案 0 :(得分:1)

这是使用withMemoryRebound执行该操作的方法: 在这种情况下,容量为1,因为您只查看结果数组的第一个元素。

let arr = UnsafePointer<UInt8>(buf).advanced(by: off)
let msk = arr.withMemoryRebound(to: UInt32.self, capacity: 1) { p in
    return p[0].bigEndian & 0x7fffffff
}

答案 1 :(得分:0)

我认为你正在寻找这样的东西:

let ppp = UnsafePointer<UInt8>(buf).advanced(by: off)
let arr = unsafeBitCast(ppp, to: UnsafeMutablePointer<UInt32>.self)