How to use UnsafeMutableRawPointer to fill an array?

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

    Another option is to create an array of the appropriate size and pass the address to the underlying storage to the function:

    var pixelData = Array(repeating: float4(), count: myTextureSizeInFloat4)
    pixelData.withUnsafeMutableBytes {
        texture.getBytes($0.baseAddress!, ...)
    }
    

    Inside the closure, $0 is a UnsafeMutableRawBufferPointer representing the array storage as a collection of bytes, and $0.baseAddress is a pointer to the first byte.

提交回复
热议问题