c - 从 cudaBindTexture2D 读取

标签 c cuda nvidia

我一直在尝试将 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 的设备内存分配完全损坏。您正在尝试将设备内存分配给已在主机上分配的二维数组。 尝试这样做将导致内存损坏和未定义的行为。设备内存分配需要一个单独的指针变量,分配后应将内存从主机复制到设备。

  • cudaMallocPitch 的第三个参数期望内存宽度(以字节为单位);不是元素。

  • 纹理只能绑定(bind)到设备内存,因此 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;
}

关于c - 从 cudaBindTexture2D 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27964995/

相关文章:

c++ - CUDA - 将 RGB 图像转换为灰度

cuda - 如何在CUDA中使用二级缓存

c - 用于检查字符串是否为回文的递归 bool 函数

c - 在这个打印两个数字之间的素数的程序中,编译器发出警告 "Parameter a and n are never used"— 这是什么意思?

从 C 中的不同文件调用方法

c - 预期 ';' 在 'static' 错误之前出现,仅在使用 gcc 编译时发生在 ubuntu 而不是 windows

c++ - GTX 550 Ti显卡支持的动态并行编程?

大型矩阵的 CUDA 矩阵乘法中断

cuda - 如何正确地将全局内存中的读取合并到具有 short 或 char 类型元素的共享内存中(假设每个元素一个线程)?

pytorch - 在使用 Python 3.7 的 WSL2 conda 环境中的系统错误中找不到 NVIDIA 驱动程序