Search code examples
c++cudathrust

From thrust::device_vector to raw pointer and back?


I understand how to go from a vector to a raw pointer but im skipping a beat on how to go backwards.

// our host vector
thrust::host_vector<dbl2> hVec;

// pretend we put data in it here

// get a device_vector
thrust::device_vector<dbl2> dVec = hVec;

// get the device ptr
thrust::device_ptr devPtr = &d_vec[0];

// now how do i get back to device_vector?
thrust::device_vector<dbl2> dVec2 = devPtr; // gives error
thrust::device_vector<dbl2> dVec2(devPtr); // gives error

Can someone explain/point me to an example?


Solution

  • You initialize and populate thrust vectors just like standard containers, i.e. via iterators:

    #include <thrust/device_vector.h>
    #include <thrust/device_ptr.h>
    
    int main()
    {
      thrust::device_vector<double> v1(10);                    // create a vector of size 10
      thrust::device_ptr<double> dp = v1.data();               // or &v1[0]
    
      thrust::device_vector<double> v2(v1);                    // from copy
      thrust::device_vector<double> v3(dp, dp + 10);           // from iterator range
      thrust::device_vector<double> v4(v1.begin(), v1.end());  // from iterator range
    }
    

    In your simple example there's no need to go the detour via pointers, as you can just copy the other container directly. In general, if you have a pointer to the beginning of an array, you can use the version for v3 if you supply the array size.