How to use UnsafeMutableRawPointer to fill an array?

前端 未结 5 1992
傲寒
傲寒 2021-02-09 02:25

I have a Metal texture, I want to access its data from Swift by making it a float4 array (so that I can access each pixel 4 color components).

I discovered this method

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-09 02:26

    This is 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)
    }
    

提交回复
热议问题