How to get bytes out of an UnsafeMutableRawPointer?

后端 未结 4 1130
孤独总比滥情好
孤独总比滥情好 2020-12-02 21:05

How does one access bytes (or Int16\'s, floats, etc.) out of memory pointed to by an UnsafeMutableRawPointer (new in Swift 3) handed to a Swift function by a C API (Core Aud

4条回答
  •  伪装坚强ぢ
    2020-12-02 21:31

    Here's a Swift 4 example of converting a literal UInt8 array to an UnsafeMutableRawPointer and back to an UInt32 array

    static func unsafePointerTest() {
        //let a : [UInt8] = [0,0,0,4,0,0,0,8,0,0,0,12]
        let a : [UInt8] = [0x04, 0x00, 0x00, 0x00,
                           0x08, 0x00, 0x00, 0x00,
                           0x0C, 0x00, 0x00, 0x00] //little endian
        //0xFF, 0xF0, 0xF0, 0x12]  //317780223 = 12F0F0FF
        let b:UnsafeMutableRawPointer = UnsafeMutableRawPointer(mutating:a)
        let bTypedPtr = b.bindMemory(to: UInt32.self, capacity: a.count/4)
        let UInt32Buffer = UnsafeBufferPointer(start: bTypedPtr, count: a.count/4)
        let output = Array(UInt32Buffer)
        print(output)
    }
    

提交回复
热议问题