How to use UnsafeMutableRawPointer to fill an array?

前端 未结 5 1990
傲寒
傲寒 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:40

    Details

    • Xcode 11.2.1 (11B500), Swift 5.1

    Solution

    extension UnsafeMutableRawPointer {
        func toArray(to type: T.Type, capacity count: Int) -> [T]{
            let pointer = bindMemory(to: type, capacity: count)
            return Array(UnsafeBufferPointer(start: pointer, count: count))
        }
    }
    

    Usage

    var array = [1,2,3,4,5]
    let ponter = UnsafeMutableRawPointer(mutating: array)
    print(ponter.toArray(to: Int.self, capacity: array.count))
    

提交回复
热议问题