I did this with an array of particles, which I pass to the computational shader.
In a nutshell, I define some constants and declare some mutable pointers and a mutable buffer pointer:
let particleCount: Int = 1048576 var particlesMemory:UnsafeMutablePointer<Void> = nil let alignment:UInt = 0x4000 let particlesMemoryByteSize:UInt = UInt(1048576) * UInt(sizeof(Particle)) var particlesVoidPtr: COpaquePointer! var particlesParticlePtr: UnsafeMutablePointer<Particle>! var particlesParticleBufferPtr: UnsafeMutableBufferPointer<Particle>!
When I set up the particles, I fill in the pointers and use posix_memalign () to allocate memory:
posix_memalign(&particlesMemory, alignment, particlesMemoryByteSize) particlesVoidPtr = COpaquePointer(particlesMemory) particlesParticlePtr = UnsafeMutablePointer<Particle>(particlesVoidPtr) particlesParticleBufferPtr = UnsafeMutableBufferPointer(start: particlesParticlePtr, count: particleCount)
The cycle for filling particles is slightly different - I now iterate over the buffer pointer:
for index in particlesParticleBufferPtr.startIndex ..< particlesParticleBufferPtr.endIndex { [...] let particle = Particle(positionX: positionX, positionY: positionY, velocityX: velocityX, velocityY: velocityY) particlesParticleBufferPtr[index] = particle }
Inside the applyShader () function, I create a copy of the memory that is used both in the input and output buffers:
let particlesBufferNoCopy = device.newBufferWithBytesNoCopy(particlesMemory, length: Int(particlesMemoryByteSize), options: nil, deallocator: nil) commandEncoder.setBuffer(particlesBufferNoCopy, offset: 0, atIndex: 0) commandEncoder.setBuffer(particlesBufferNoCopy, offset: 0, atIndex: 1)
... and after running the shader, I put the shared memory (particleMemory) back in the buffer pointer:
particlesVoidPtr = COpaquePointer(particlesMemory) particlesParticlePtr = UnsafeMutablePointer(particlesVoidPtr) particlesParticleBufferPtr = UnsafeMutableBufferPointer(start: particlesParticlePtr, count: particleCount)
There is an updated version of Swift 2.0 of this in my GitHub repository here