如何将字符指针从设备复制到主机

时间:2019-11-29 23:19:45

标签: cuda

我希望主变量中的“ 文本”变量中包含“ 一些文本”。如何使用 cudaMemcpyFromSymbol()实现此目标?

__device__ char* pointerToSomething;

__global__ void DoSomething()
{
   pointerToSomething = "some text";
}

int main()
{
   char text;
}

1 个答案:

答案 0 :(得分:0)

仅通过一次调用cudaMemcpyFromSymbol便无法完成操作(这将需要2个复制步骤),并且您无法在声明为char text;的变量中存储9个字符的文本

因此,只要提到这两个项目,您就可以这样做:

$ cat t1606.cu
#include <iostream>
__device__ char* pointerToSomething;
__global__ void DoSomething()
{
   pointerToSomething = "some text";
}

int main()
{
   char text[32] = {0};
   char *data;
   DoSomething<<<1,1>>>();
   cudaMemcpyFromSymbol(&data, pointerToSomething, sizeof(char *));
   cudaMemcpy(text, data, 9, cudaMemcpyDeviceToHost);
   std::cout << text << std::endl;
}
$ nvcc -o t1606 t1606.cu
t1606.cu(5): warning: conversion from a string literal to "char *" is deprecated

t1606.cu(5): warning: conversion from a string literal to "char *" is deprecated

$ cuda-memcheck ./t1606
========= CUDA-MEMCHECK
some text
========= ERROR SUMMARY: 0 errors
$

它与printf的工作方式相同:

$ cat t1606.cu
#include <cstdio>
__device__ char* pointerToSomething;
__global__ void DoSomething()
{
   pointerToSomething = "some text";
}

int main()
{
   char text[32] = {0};
   char *data;
   DoSomething<<<1,1>>>();
   cudaMemcpyFromSymbol(&data, pointerToSomething, sizeof(char *));
   cudaMemcpy(text, data, 9, cudaMemcpyDeviceToHost);
   printf("%s\n", text);
}
$ nvcc -o t1606 t1606.cu
t1606.cu(5): warning: conversion from a string literal to "char *" is deprecated

t1606.cu(5): warning: conversion from a string literal to "char *" is deprecated

$ cuda-memcheck ./t1606
========= CUDA-MEMCHECK
some text
========= ERROR SUMMARY: 0 errors
$
相关问题