0

I would like to dereference a pointer and assign it a value in a Metal Shader (Kernel), like so (simple example);

kernel void test_kernel()
{
    device uint64_t* ptr;
    *ptr = 1;
}

When I run this I get the following error;

Execution of the command buffer was aborted due to an error during execution. 
Caused GPU Hang Error (00000003:kIOGPUCommandBufferCallbackErrorHang)

This is caused by the line, *ptr = 1.

Am I missing something here? Can you dereference a device pointer in Metal Shader?

  • How do you expect this piece of code to work? All `device` and `constant` pointers such as `ptr` has to point somewhere, which basically means that it has to be inside any of the resident `MTLBuffer`s – JustSomeGuy Apr 28 '22 at 18:19
  • And to answer your question, yes, you can dereference and assign pointers in Metal – JustSomeGuy Apr 28 '22 at 18:19
  • @JustSomeGuy, thanks! So, should this work if I use ```thread uint64_t* ptr;```? Testing this, it also doesn't work, I get same result. Is it possible to create an MTLBuffer within a kernel, or does this all need to be assigned before calling the kernel? – fuzzy_motion Apr 29 '22 at 09:17
  • `thread` pointer also needs to point somewhere. You can do something like `char buffer[128]; thread uint64_t* ptr = (thread uint64_t*)buffer;` But I'm not sure how that's gonna be useful. Otherwise, yes, all the memory has to be allocated before running the kernel. If you do need an "allocator" I suggest allocating a big buffer upfront and having an `atomic_uint` offset in `device` space into that big buffer that you use to suballocate chunks of that buffer. Just make sure that the contention isn't too high on the atomic: basically, that every single buffer doesn't try to allocate own chunk. – JustSomeGuy Apr 29 '22 at 18:12
  • Think about it in terms of just regular C code running on CPU. If you declare a `uint64_t* ptr;` and don't initialize it, where it's gonna point? It will point to garbage and most probably lead to a page-fault when you use it, especially in non-debug builds. – JustSomeGuy Apr 29 '22 at 18:14
  • Oh, there's one more option: you can also allocate `threadgroup` memory. – JustSomeGuy Apr 29 '22 at 18:19

0 Answers0