[英]Passing char array to CUDA Kernel
我正在尝试将包含从主要功能中的txt文件读取的10000个单词的char数组传递给CUDA内核功能。
单词从主机传输到设备,如下所示:
(主要功能代码:)
//.....
const int text_length = 20;
char (*wordList)[text_length] = new char[10000][text_length];
char *dev_wordList;
for(int i=0; i<number_of_words; i++)
{
file>>wordList[i];
cout<<wordList[i]<<endl;
}
cudaMalloc((void**)&dev_wordList, 20*number_of_words*sizeof(char));
cudaMemcpy(dev_wordList, &(wordList[0][0]), 20 * number_of_words * sizeof(char), cudaMemcpyHostToDevice);
//Setup execution parameters
int n_blocks = (number_of_words + 255)/256;
int threads_per_block = 256;
dim3 grid(n_blocks, 1, 1);
dim3 threads(threads_per_block, 1, 1);
cudaPrintfInit();
testKernel<<<grid, threads>>>(dev_wordList);
cudaDeviceSynchronize();
cudaPrintfDisplay(stdout,true);
cudaPrintfEnd();
(内核功能代码:)
__global__ void testKernel(char* d_wordList)
{
//access thread id
const unsigned int bid = blockIdx.x;
const unsigned int tid = threadIdx.x;
const unsigned int index = bid * blockDim.x + tid;
cuPrintf("!! %c%c%c%c%c%c%c%c%c%c \n" , d_wordList[index * 20 + 0],
d_wordList[index * 20 + 1],
d_wordList[index * 20 + 2],
d_wordList[index * 20 + 3],
d_wordList[index * 20 + 4],
d_wordList[index * 20 + 5],
d_wordList[index * 20 + 6],
d_wordList[index * 20 + 7],
d_wordList[index * 20 + 8],
d_wordList[index * 20 + 9]);
}
有没有一种方法可以更轻松地操作它们? (我想每个元素/位置有一个单词)我尝试过<string>
,但是我不能在CUDA设备代码中使用它们。
cuPrintf("%s\n", d_wordlist+(index*20));
应该管用? (前提是您的字符串以零结尾)
更新:
这行:
char (*wordList)[text_length] = new char[10000][text_length];
我看起来很奇怪 通常,指向char的指针数组将如下分配:
char** wordList = new char*[10000];
for (int i=0;i<10000;i++) wordList[i] = new char[20];
在这种情况下,wordList [i]将是指向字符串编号i的指针。
更新#2:
如果您需要将字符串存储为连续的块,并且确定没有任何字符串超过text_length + 1,则可以这样做:
char *wordList = new char[10000*text_length];
for(int i=0; i<number_of_words; i++)
{
file>>wordList+(i*text_length);
cout<<wordList+(i*text_length)<<endl;
}
在这种情况下,wordList +(i * text_length)将指向字符串编号i的开头,并且将以0终止,因为这是您从文件中读取它的方式,并且可以使用此答案中指定的方式。 但是,如果任何字符串长于text_length-1,您仍然会遇到问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.