Search code examples
iosswiftmetal

Pointer (memory) alignment to 16K in Swift for Metal buffer creation


I'd like to createa Metal buffers with the newBufferWithBytesNoCopy function for letting CPU and GPU share memory and practicing zero-copy data transfer.

The newBufferWithBytesNoCopy function takes a UnsafeMutablePointer-type pointer, and the pointer needs to be aligned to 16K(16384) bytes.

Could anyone provide advice on how to create a aligned memory to a certain size in Swift?


Solution

  • I believe this should work for you:

    var memory:UnsafeMutablePointer<Void> = nil
    var alignment:UInt = 0x4000 // 16K aligned
    var size:UInt = bufferSize // bufferSize == your buffer size
    
    posix_memalign(&memory, alignment, size)
    

    For reference:

    http://pubs.opengroup.org/onlinepubs/009695399/functions/posix_memalign.html