我有以下 vector :

thrust::host_vector< T , thrust::cuda::experimental::pinned_allocator< T > > h_vector

在我当前的情况下,其中T的类型为float。我想从重点出发,以正确的方式访问第i个元素。

天真的方法是:
float el = h_vector[i];

导致以下错误:
../src/gpu.cuh(134): error: a reference of type "float &" (not const-qualified) cannot be initialized with a value of type "thrust::host_vector<float, thrust::system::cuda::experimental::pinned_allocator<float>>"

显然,h_array [i]类型是reference,所以我继续尝试使用thrust::raw_refence_castthrust::pointer检索我的float数据无济于事。

最后,我想出了:
    float *raw = thrust::raw_pointer_cast(h_array->data());
    float el = raw[i];

有没有更好的方法可以做到这一点?

编辑:原型(prototype)代码
#include <thrust/host_vector.h>
#include <thrust/system/cuda/experimental/pinned_allocator.h>

static const int DATA_SIZE = 1024;

int main()
{

    thrust::host_vector<float, thrust::cuda::experimental::pinned_allocator<float> > *hh = new thrust::host_vector<float, thrust::cuda::experimental::pinned_allocator<float> >(DATA_SIZE);
    float member, *fptr;
    int i;

//  member = hh[1]; //fails

    fptr = thrust::raw_pointer_cast(hh->data()); //works
    member = fptr[1];
    return 0;
}

编辑2 :
我实际上将 vector 用作此 vector :
thrust::host_vector< T , thrust::cuda::experimental::pinned_allocator< T > > *h_vector

使我的原始问题完全令人误解。

最佳答案

我不知道为什么您的代码中需要这种复杂程度。您是否看过我发布here的示例?

无论如何,这行代码:

   thrust::host_vector<float, thrust::cuda::experimental::pinned_allocator<float> > *hh = new thrust::host_vector<float, thrust::cuda::experimental::pinned_allocator<float> >(DATA_SIZE);

创建指向 vector 的指针。那和 vector 不一样。

使用这样的构造:
member = hh[1];

hh是指向 vector 的指针时,这不是尝试访问 vector 中元素的有效方法。这将是索引 vector 数组的有效方法,这不是您要尝试执行的操作。

另一方面,如果您这样做:
member = (*hh)[1];

我相信您的编译错误将会消失。它对我有用。

请注意,我认为这不是CUDA或问题。我在尝试使用std::vector时遇到类似的麻烦。还要注意,在原始问题中,您没有指示h_vector是指向 vector 的指针,并且您显示的代码行并未以这种方式创建它。因此,您的编辑/原型(prototype)代码与您的原始描述明显不同。

10-08 08:28
查看更多