How to use UnsafeMutableRawPointer to fill an array?

前端 未结 5 1984
傲寒
傲寒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 02:44

    First, let's assume you have a UnsafeRawPointer and a length:

    let ptr: UnsafeRawPointer = ...
    let length: Int = ...
    

    Now you want to convert that to an [float4]. First, you can convert your UnsafeRawPointer to a typed pointer by binding it to a type:

    let float4Ptr = ptr.bindMemory(to: float4.self, capacity: length)
    

    Now you can convert that to a typed buffer pointer:

    let float4Buffer = UnsafeBufferPointer(start: float4Ptr, count: length)
    

    And since a buffer is a collection, you can initialize an array with it:

    let output = Array(float4Buffer)
    

    For much more on working with UnsafeRawPointer, see SE-0138, SE-0107, and the UnsafeRawPointer Migration Guide.

提交回复
热议问题