Eduardo
Eduardo

Reputation: 77

Accessing an host_vector item (thrust library) allocated with the pinned_allocator

I have the following vector:

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

where T, in my current case, is of type float. I would like to access the i-th element in a correct fashion from the thrust point of view.

The naïve approach was:

float el = h_vector[i];

which resulted in the following error:

../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>>"

Apparently, the h_array[i] type is reference, so i went on trying to use thrust::raw_refence_cast and thrust::pointer to retrieve my float data to no avail.

In the end, i came up with:

    float *raw = thrust::raw_pointer_cast(h_array->data());
    float el = raw[i];

Is there a better way to accomplish this?

EDIT: prototype code

#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;
}

EDIT 2: I actually used the vector as this one:

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

rendering my original question completely misleading.

Upvotes: 1

Views: 572

Answers (1)

Robert Crovella
Robert Crovella

Reputation: 152053

I don't know why you need this level of complication in your code. Did you look at the example I posted here?

Anyway, this line of code:

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

creates a pointer to vector. That is not the same thing as a vector.

Using a construct like this:

member = hh[1];

when hh is a pointer to a vector is not a valid way of attempting to access an element in the vector. This would be a valid way of indexing into an array of vectors, which is not what you are trying to do.

If you do this on the other hand:

member = (*hh)[1];

I believe your compile error will go away. It does for me.

Note that I don't think this is a CUDA or thrust issue. I run into similar trouble trying your approach with std::vector. Also note that nowhere in your original question did you indicate that h_vector was a pointer to a vector, and the line of code that you did show did not create it that way. So your edited/prototype code differs markedly from your original description.

Upvotes: 2

Related Questions