首页 > 解决方案 > 如何将字符指针从设备复制到主机

问题描述

我想在主要的“文本”变量中包含“一些文本”。如何使用cudaMemcpyFromSymbol()来实现这一点?

__device__ char* pointerToSomething;

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

int main()
{
   char text;
}

标签: cuda

解决方案


它不能只通过一次调用来完成cudaMemcpyFromSymbol(它将需要 2 个复制步骤),并且您不能将 9 个字符的文本存储在声明为的变量中char text;

因此,对于提到的这两个项目,您可以这样做:

$ 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
$

推荐阅读