将一个SIMD4<Float>发送到Metal缓冲区。

huangapple go评论62阅读模式
英文:

Send a SIMD4<Float> to a Metal buffer

问题

我有一个被定义为SIMD4<Float>的颜色,并且想要将它发送到一个Metal缓冲区,如下所示:

var color = SIMD4<Float>(1, 0, 0, 0)

var colorBuffer: MTLBuffer!

let size = MemoryLayout<SIMD4<Float>>.size
colorBuffer = Renderer.device.makeBuffer(bytes: color, length: size)

但是这样做是行不通的,因为根据Xcode提供的错误信息,bytes必须是一个UnsafeRawPointer

Cannot convert value of type 'SIMD4<Float>' to expected argument type 'UnsafeRawPointer'

那么我该如何获得color变量的UnsafeRawPointer呢?

英文:

I have a color defined as a SIMD4&lt;Float&gt; and would like to send it to a Metal buffer as shown below:

var color = SIMD4&lt;Float&gt;(1, 0, 0, 0)

var colorBuffer: MTLBuffer!

let size = MemoryLayout&lt;SIMD4&lt;Float&gt;&gt;.size
colorBuffer = Renderer.device.makeBuffer(bytes: color, length: size)

But this does not work because bytes must be an UnsafeRawPointer as seen from the error message provided by Xcode:

Cannot convert value of type &#39;SIMD4&lt;Float&gt;&#39; to expected argument type &#39;UnsafeRawPointer&#39;

So how do I get the UnsafeRawPointer for the color variable?

答案1

得分: 0

将颜色变量作为指针传递,使用&符号。例如:

colorBuffer = Renderer.device.makeBuffer(bytes: &color, length: size)
英文:

Pass in the color var with an & which provides a pointer. eg.

colorBuffer = Renderer.device.makeBuffer(bytes: &amp;color, length: size)

答案2

得分: 0

您可以使用MTLBuffercontents属性返回的UnsafeMutableRawPointer上的func storeBytes&lt;T&gt;(of: T, toByteOffset: Int, as: T.Type)方法来实现,示例如下:

var color = SIMD4<Float>(1, 0, 0, 0)

var colorBuffer: MTLBuffer!

let size = MemoryLayout<SIMD4<Float>>.size
colorBuffer = Renderer.device.makeBuffer(bytes: color, length: size)
colorBuffer.contents.storeBytes(of: color, toByteOffset: 0, as: SIMD4<Float>.self)

这段代码将color的值存储到了colorBuffer的内存中,偏移量为0。

英文:

You could use func storeBytes&lt;T&gt;(of: T, toByteOffset: Int, as: T.Type) on the UnsafeMutableRawPointer that is returned by contents property of the MTLBuffer like this:

var color = SIMD4&lt;Float&gt;(1, 0, 0, 0)

var colorBuffer: MTLBuffer!

let size = MemoryLayout&lt;SIMD4&lt;Float&gt;&gt;.size
colorBuffer = Renderer.device.makeBuffer(bytes: color, length: size)
colorBuffer.contents.storeBytes(of: color, toByteOffset: 0, as:SIMD4&lt;Float&gt;.self)

huangapple
  • 本文由 发表于 2023年8月8日 22:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定