问题
I need help to replace the contents of a MTLBuffer without creating a new one. Content in both cases are Float Arrays.
let vector:[Float] = [0,1,2,3,4,5,6,7,8,9]
let byteLength = arr1.count*MemoryLayout<Float>.size
let buffer = metalDevice.makeBuffer(bytes: &vector, length: byteLength, options: MTLResourceOptions())
let vector2:[Float] = [10,20,30,40,50,60,70,80,90]
I understand buffer.contents() gives us a UnsafeMutableRawPointer. I would like to create a new UnsafeMutableRawPointer from vector2 and replace the contents of buffer.
Thanks in advance!
回答1:
You can do this with memcpy
, but the slightly Swiftier way is:
buffer.contents().copyBytes(from: vector2, count: vector2.count * MemoryLayout<Float>.stride)
In general, prefer stride
over size
when calculating the length of an array in bytes. If the type is not primitive and has any padding, size
will not account for this, and you'll copy fewer bytes than you intended.
来源:https://stackoverflow.com/questions/42561558/update-contents-of-mtlbuffer-in-metal