Search code examples
metal

How to define a writable integer as parameter in the kernel function?


I tried to create a kernel with parameter

device int &errorC [[ buffer(2) ]],

and set the buffer using

[encoder setBytes:&count length:sizeof(int) atIndex: 2];

But I receives error message saying that failed assertion Compute Function: Bytes are being bound at index 2 to a shader argument with write access enabled.'

Why? It seems that I should not use setBytes. But how can I set an integer and the kernel can write back to it?


Solution

  • The -setBytes:... method can only provide constant data, not writable device data. This method of providing data can be more efficient than providing a buffer of your own precisely because it may (behind the scenes) not use a writable buffer to hold the data.

    Among other things, if you want the CPU to be able to read the value written to errorC, note that there's no way when you use -setBytes:.... There's no -getBytes... method.

    If you want the data to be writable, you do need to provide a buffer using the -setBuffer:offset:atIndex: method.