2016-11-16 60 views
3

我正在從Swift 2遷移到Swift 3,並且我被困在一個點上。Swift 3 Unsafe指針

斯威夫特2

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

我得到第一線的錯誤說

是 'init' 是不可用:使用 'withMemoryRebound(到:容量:__)' 來 臨時查看內存作爲另一種佈局兼容類型。

我試圖使用withMemoryoRebound方法,但我不確定參數。 按照this docuentation,UnsafePointer<>已被UnsafeRawPointer取代。所以我改變了我的代碼如下

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

但這裏的第二行,它說

類型「UnsafeRawPointer」無標會員

我怎樣才能成功地將其轉換爲斯威夫特3?

+1

這可能是你在找什麼:?如何獲得字節出UnsafeMutableRawPointer的(http://stackoverflow.com/questions/38983277/how-to-get-bytes-out-of -an-unsafemutablerawpointer) –

回答

0

我認爲你正在尋找的東西是這樣的:

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

這是如何使用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 
}