Update contents of MTLBuffer in Metal

2019-04-09 20:55发布

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!

标签: ios metal
1条回答
闹够了就滚
2楼-- · 2019-04-09 21:24

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.

查看更多
登录 后发表回答