0

This seems to be a silly question, but I can't find a good way to loop through an array and currently, I have to pass a buffer that contains the element count to my kernel function.

kernel void test_func(constant const int2* array [[ buffer(0) ]],
                      constant const int& arrayCount [[ buffer(1) ]],
                      device half4* result [[ buffer(2) ]],
                      uint2 pos [[thread_position_in_grid]]) {
  // some code to end early if pos is outside of my data
  for(ulong i = 0; i < sizeof(array) / sizeof(int2) /*(ulong) arrayCount*/; i += 1 ) {
    // do something
  }
}

Calculation using sizeof always yields incorrect results, on the other hand, using the count buffer return correct results. Seems like MSL doesn't support for each loop of c++ 11.
There should be a better way to do this, right?

Son Nguyen
  • 1,124
  • 2
  • 10
  • 24
  • Yes. Any array is a pointer to first element and a number of elements. All the buffer bind points are just pointers (or you could make them references, but that doesn't matter in this case). Those bind points don't know how big the data bound to them is. So you have to pass the array size separately. – JustSomeGuy Jan 11 '23 at 21:37
  • Looooong time ago, when I coded a bit with C, I remember it has has a `null` ending byte or something like that to mark the end of a pointer, that's how `sizeof` work, right? – Son Nguyen Jan 12 '23 at 03:35
  • It's only for strings. And I mean, even if it did. 1) You wouldn't be able to have zeroes in your arrays. 2) You would have to go through all the elements of the array each time you needed the length. – JustSomeGuy Jan 12 '23 at 04:42

0 Answers0