c++ - GPU 设备函数如何访问主机函数中定义的类对象?

标签 c++ cuda gpu

我有一个现有的 C++ 程序,我想将它迁移到 GPU 版本。内核函数需要访问宿主函数中定义的类对象。例如,stringstream 对象将在线程中使用。但是在Cuda中编译失败。内核函数如何访问宿主函数中定义的此类类对象?

这是一个例子。

#include <cstdio>
#include <sstream>

using namespace std;

__global__ void kernel(stringstream * sstr)
{
    printf("%s\n", sstr->str());
}

int main(int argc, char ** argv)
{
    stringstream * sstr;
    cudaMallocManaged(&sstr, sizeof(stringstream));
    *sstr  << "Hello world\n";
    kernel<<<32, 32>>>(sstr);
    cudaDeviceSynchronize();
    cudaFree(sstr);
    return 0;
}

我得到以下编译错误。

$ nvcc -o bin src.cu
src.cu(8): warning: non-POD class type passed through ellipsis

src.cu(8): error: calling a __host__ function("std::__cxx11::basic_stringstream<char,  ::std::char_traits<char> , std::allocator<char> > ::str const") from a __global__ function("kernel") is not allowed

src.cu(8): error: identifier "std::__cxx11::basic_stringstream<char,  ::std::char_traits<char> , std::allocator<char> > ::str const" is undefined in device code

src.cu(8): error: calling a __host__ function("std::__cxx11::basic_string<char,  ::std::char_traits<char> , std::allocator<char> > ::~basic_string") from a __global__ function("kernel") is not allowed

src.cu(8): error: identifier "std::__cxx11::basic_string<char,  ::std::char_traits<char> , std::allocator<char> > ::~basic_string" is undefined in device code

4 errors detected in the compilation of "/tmp/tmpxft_00003bd0_00000000-8_src.cpp1.ii".

最佳答案

你不应该在你的内核中使用 C++ std 类,因为 std::stringstream 相关函数是从你的操作系统预编译和链接的,nvcc 不会生成相应的 __device__ 函数。

看这个topic

关于c++ - GPU 设备函数如何访问主机函数中定义的类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56792516/

相关文章:

c++ - Gecode,使用 gecode.int.hh 编译程序时出错

c++ - 强名称 dll - 如何排除故障?

c++ - 指向常量指针常量数组的常量指针

cuda - 从多个进程并行执行GPU内核

c++ - ptxas 文件中的 CUDA 外部类链接和未解析的外部函数

c++ - CUDA 代码在 Linux 上编译但在 Windows 上不编译(Visual Studio 2012)

linux - pci_lookup_name 怎么来的?

cuda - GPU上的 float 除法与CPU上的 float 除法

algorithm - 关于数据并行编程和算法的好书和资源

c++ - 在 c_str()、length() 和 size() 之间发现不一致