Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use UnsafeMutableRawPointer to fill an array?

Tags:

swift

metal

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 of MTLTexture :

getBytes(UnsafeMutableRawPointer, bytesPerRow: Int, bytesPerImage: Int, from: MTLRegion, mipmapLevel: Int, slice: Int)

I don't know at all how to use UnsafeMutableRawPointer, how it works, and how to get the data back into a simple Swift array.

My first attempt was to create a pointer and allocate enough space like that, but I don't even know if that's what I should do:

var pointer = UnsafeMutableRawPointer.allocate(bytes: myTextureSizeInBytes, alignedTo: 0)  

Then I have no idea at all of how to get this data back into a standard Swift array...

Thank you.

like image 625
Pop Flamingo Avatar asked Jan 10 '17 17:01

Pop Flamingo


2 Answers

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.

like image 190
Rob Napier Avatar answered Oct 20 '22 16:10

Rob Napier


Details

  • Xcode 11.2.1 (11B500), Swift 5.1

Solution

extension UnsafeMutableRawPointer {
    func toArray<T>(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))
like image 24
Vasily Bodnarchuk Avatar answered Oct 20 '22 15:10

Vasily Bodnarchuk