c++ - 如何访问 thrust::device_vector<struct> 的成员

标签 c++ vector cuda thrust

<分区>

CUDA 在此处找到了一些文档:https://docs.nvidia.com/cuda/thrust/index.html#vectors这允许在设备内存/代码中使用 vector 。我正在尝试创建一个结构类型的 vector 以用于一般处理。这是示例代码:

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <iostream>

struct Data
{
  double first, second, total;
};

__global__
void add(thrust::device_vector<Data> *d_matrix)
{
  &d_matrix[1].total = &d_matrix[1].first + &d_matrix[1].second;
}

int main()
{
  thrust::host_vector<Data> matrix;
  thrust::device_vector<Data> *d_matrix;
  int size = sizeof(thrust::host_vector<Data>);

  matrix[1].first = 2100;
  matrix[1].second = 100;

  cudaMalloc(&d_matrix, size);

  cudaMemcpy(d_matrix, &matrix, size, cudaMemcpyHostToDevice);

  add<<<1,1>>>(d_matrix);

  cudaMemcpy(&matrix, d_matrix, size, cudaMemcpyDeviceToHost);

  cudaFree(d_matrix);

  std::cout << "The sum is: " << matrix[1].total;

  return 0;
}

我收到以下错误:

gpuAnalysis.cu(13): error: class "thrust::device_vector>" has no member "total"

gpuAnalysis.cu(13): error: class "thrust::device_vector>" has no member "first"

gpuAnalysis.cu(13): error: class "thrust::device_vector>" has no member "second"

3 errors detected in the compilation of "/tmp/tmpxft_000013c9_00000000-8_gpuAnalysis.cpp1.ii".

根据 nvidia 网站上提供的文档,这些 vector 能够将所有数据类型存储为 std::vector。有没有办法修复此错误以使用每个 vector 元素访问结构的成员?

最佳答案

void add(thrust::device_vector<Data> *d_matrix) {
   &d_matrix[1].total = &d_matrix[1].first + &d_matrix[1].second;
}

在此代码中,d_matrix参数实际上是指向 thrust::device_vector<Data> 类型对象的指针 .表达式 &d_matrix[1].total是由于 C++ 运算符优先级被评估为 d_matrix[1]被认为是一些不存在的 thrust::device_vector<Data> 类型元素数组的第二个元素,因为指针可以自动视为数组。这个(不存在的)第二个元素是 .total 的主题不存在的成员访问权限。

尝试 (*d_matrix)[1].total = ...相反。


此外,我不确定您的代码是否正确。例如,您没有指定 host_vector 的大小(元素的数量,而不是对象的大小)。也不device_vector .你也cudaMemcpy vector 对象本身;它也复制他们的内容吗?甚至允许吗?我没有使用 Thrust 的经验,但是根据 this page , 有更简单的方法来创建 device_vector .

关于c++ - 如何访问 thrust::device_vector<struct> 的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50880366/

相关文章:

c++ - 将小部件插入 QGridLayout 的问题

c - 在 CUDA 中倾斜图像

java - 如何在 JNI 中将 int 转换为 String(?)?

c++ - 从 vector 的 vector 中移除重叠

c++ - 了解我有多少内存可用于动态 vector C++

c++ - log 和 rand() 给出的不是数字

c++ - 动态并行性无效文件格式

cuda - 使用 CUDA 纹理存储 2D 表面

c++ - 如果使用 *pt = &stu1,字符串成员变为空

c# - 如何从 C++ 下标运算符所在的类中访问它?