Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update contents of MTLBuffer in Metal

Tags:

ios

metal

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!

like image 690
thewebmaker Avatar asked Mar 02 '17 17:03

thewebmaker


1 Answers

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.

like image 135
warrenm Avatar answered Sep 28 '22 18:09

warrenm