我试着在纹理内存中存储一个2D数组,并通过cudaBindTexture2D读取它
但返回的值是0,但我不确定这是否是cudaBindTexture2D和tex2D()的正确用法;
我做了一个很简单的代码来尝试:

#include <cuda.h>
#include <stdio.h>
#include <stdlib.h>
texture<uint, cudaTextureType2D, cudaReadModeElementType> tex;
__global__
void texture2DTest(int *x){
*x = tex2D(tex,0,0);

}

void initTable(int textureTable[][9]){
int i=0;
int j=0;

for(i=0; i<10; i++){
    for(j=0; j<9; j++){
        textureTable[i][j]=0;
    }
}

textureTable[0][0] = 12;

}

int main (int argc, char ** argv){

int textureTable[10][9];

int *d_x;
int x=2;

size_t pitch;

initTable(textureTable);

cudaMalloc(&d_x, sizeof(int));
cudaMemcpy(d_x, &x, sizeof(int), cudaMemcpyHostToDevice);

cudaMallocPitch( (void**)textureTable,&pitch, 9, 10);
cudaChannelFormatDesc desc = cudaCreateChannelDesc<uint>();
cudaBindTexture2D(NULL, tex, textureTable, desc, 9, 10, pitch) ;

texture2DTest<<<1,1>>>(d_x);

cudaThreadSynchronize();

cudaMemcpy(&x,d_x, sizeof(int), cudaMemcpyDeviceToHost);

printf(" \n %d \n",x);

cudaUnbindTexture(tex);

return 0;
}

谢谢您。

最佳答案

提供的代码中有很多问题。
使用cudaMallocPitch的设备内存分配完全中断您正在尝试将设备内存分配给已在主机上分配的2D阵列。
尝试这样做将导致内存损坏和未定义的行为设备内存分配需要单独的指针变量,分配后应将内存从主机复制到设备。
cudaMallocPitch的第三个参数需要以字节为单位的内存宽度;而不是元素。
纹理只能绑定到设备内存,因此cudaBindTexture需要设备内存指针作为输入。
修复以上所有问题,你的最终main将看起来像这样:

int main (int argc, char ** argv)
{

int textureTable[10][9];

int *d_x;
int x = 2;

size_t pitch;

initTable(textureTable);

cudaMalloc(&d_x, sizeof(int));
cudaMemcpy(d_x, &x, sizeof(int), cudaMemcpyHostToDevice);

int* d_textureTable; //Device texture table

//Allocate pitch linear memory to device texture table
cudaMallocPitch((void**)&d_textureTable,&pitch, 9 * sizeof(int), 10);

//Use Memcpy2D as the pitch of host and device memory may be different
cudaMemcpy2D(d_textureTable, pitch, textureTable, 9 * sizeof(int), 9 *sizeof(int), 10, cudaMemcpyHostToDevice);

cudaChannelFormatDesc desc = cudaCreateChannelDesc<uint>();
cudaBindTexture2D(NULL, tex, d_textureTable, desc, 9, 10, pitch) ;

texture2DTest<<<1,1>>>(d_x);

cudaThreadSynchronize();

cudaMemcpy(&x,d_x, sizeof(int), cudaMemcpyDeviceToHost);

printf(" \n %d \n",x);

cudaUnbindTexture(tex);
//Don't forget to free the allocated memory
cudaFree(d_textureTable);
cudaFree(d_x);
return 0;
}

10-04 12:35