英文:
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<Float>
and would like to send it to a Metal buffer as shown below:
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)
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 'SIMD4<Float>' to expected argument type 'UnsafeRawPointer'
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: &color, length: size)
答案2
得分: 0
您可以使用MTLBuffer
的contents
属性返回的UnsafeMutableRawPointer
上的func storeBytes<T>(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<T>(of: T, toByteOffset: Int, as: T.Type)
on the UnsafeMutableRawPointer
that is returned by contents
property of the MTLBuffer
like this:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论