如何使用UnsafeMutableRawPointer填充数组

如何使用UnsafeMutableRawPointer填充数组

本文介绍了如何使用UnsafeMutableRawPointer填充数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Metal纹理,我想通过使其成为float4数组来从Swift中访问其数据(这样我就可以访问每个像素4个颜色分量).

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).

我发现了MTLTexture的这种方法:

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

我根本不知道如何使用UnsafeMutableRawPointer,它如何工作以及如何将数据返回到简单的Swift数组中.

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)

然后我完全不知道如何将这些数据返回到标准Swift数组中...

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

谢谢.

推荐答案

首先,假设您有一个UnsafeRawPointer和一个长度:

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

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

现在,您要将其转换为[float4].首先,可以通过将UnsafeRawPointer绑定到类型来将其转换为类型指针:

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)

有关使用UnsafeRawPointer的更多信息,请参见 SE-0138 SE-0107 UnsafeRawPointer迁移指南.

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

这篇关于如何使用UnsafeMutableRawPointer填充数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:33