Bind CUDA Textures in a function?

Hi! I need to use about 4 different textures and they all need the same configuration (liner interpolation and normalized index), I thought I could have a cleaner code while saving a few lines by encapsulating all the setup, including the texture binding inside a function.

I read that I can’t pass a texture as a function argument in the host but I thought I could use textureReference as a workaround. So far I haven’t been able to make it work as it’s giving me problems due to the texture reference not being a constant.

Anyone has some suggestions?

Here’s a non-working pseudo-code:

texture<float, 1, cudaReadModeElementType> tex1, tex2;

void
load_tex(float *data, int length, cudaArray *data_array, 
         textureReference *tref){

    //allocate cuda array memory
    checkCudaErrors(cudaMallocArray(&data_array, &tref->channelDesc, 
                                    length, 1));

    //copy data vector to cuda array
    checkCudaErrors(cudaMemcpyToArray(data_array, 0, 0, data, 
                                      sizeof(float)*length,
                                      cudaMemcpyHostToDevice));

    //bind array to texture
    checkCudaErrors(cudaBindTextureToArray(&tref, data_array));

    //set texture parameters
    tref->addressMode[0] = cudaAddressModeBorder;
    tref->addressMode[1] = cudaAddressModeBorder;
    tref->filterMode = cudaFilterModeLinear;
    tref->normalized = true;
}

int main(){
    textureReference *tref;
    cudaArray *data_array1, *data_array2;
    float *data1, *data2;
    int length = 10;
    
    //initialize, allocate and populate data
    // ...

    //load textures using functions
    cudaGetTextureReference(&tref, &tex1);
    load_tex(data1, length, data_array1, &tref);
    cudaGetTextureReference(&tref, &tex2);
    load_tex(data2, length, data_array2, &tref);
}

Hi,

I think your problem is over here:

and

In the function load_text, you are receiving a pointer of kind textureReference, however, you are passing a pointer to a reference of textureReference. Basically, with

load_tex(data1, length, data_array1, &tref);

You are passing in the last argument a datatype of kind textureReference ** and not textureReference *. So basically, you will need to fix the load_tex function to be consistent, changing the argument and also this kind of lines &tref->channelDesc to &(*(tref)->channelDesc) and so on.

Regards,
Leon.