Search code examples
iosswiftbuffermetal

MTLBuffer contents causing EXC_BAD_ACCESS


I created an buffer filled in by an array of float values. Unfortunately, when I try to query its contents() property (when I was trying to debug a problem), I was getting an EXC_BAD_ACCESS. Here's the code:

let inputData  = [Float32](repeatElement(5, count: 16384)) // Declaration

// Declaration of the buffer and filling contents...
inputBuffer = device.makeBuffer(bytes: inputData, length: MemoryLayout<Float32>.size * inputData.count, options: MTLResourceOptions()) 

// Crash occurs here:
let contents = inputBuffer.contents().load(as: [Float32].self)

I would like to know why the crash occurs. Other similar buffer declarations have worked correctly, so I guess this might be an issue with accessing the contents.


Solution

  • To access the array contents, using the load method, you need to specify the array element type (and an optional offset) instead. For instance:

    let firstElement = inputBuffer.contents().load(fromByteOffset: 0, as: Float.self)
    

    and so on. You were trying to load the first element as a [Float] which might explain the crash.