metalmetalkit

Array length in Metal Shading Language


Can anyone help on getting the array length in MSL?

It doesn't work as expected when I am passing an array through a function, however it's working within the same function.

uint arr[] = { 4, 3, 8, 5, 3, 32, 5, 7, 8};

Tried:

size_t size = sizeof(arr) / sizeof(arr[0])

is returning: 2

size_t size = *(&arr + 1) - arr;

is returning: 0

Shader:

float4 testSize(uint arr[], float2 uv) {
    size_t size = sizeof(arr) / sizeof(arr[0]);
    return float4(fract(uv.x * size), 0, 0, 1);
}
fragment float4 testFrag(VertexOut input[[stage_in]]) {
    float2 uv = input.textureCoordinate;
    uint text[] = {4, 3, 8, 5, 3, 32, 5, 7, 8};
    float4 col = testSize(text, uv);
    return col;
}

Thanks


Solution

  • Unfortunately it's not possible, you need to also pass the size of the array to the function.

    When you pass in the array to your function, you are really passing in the address of the first element in that array. So the pointer is only pointing to the first element once inside your function.

    Therefore, sizeof() function will return the number of bytes allocated for the pointer rather than the whole array.