从thrust :: device_vector到原始指针再回来?

时间:2011-10-06 18:48:33

标签: thrust

我理解如何从矢量转到原始指针但我跳过了如何倒退的节拍。

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

有人可以向我解释/指出一个例子吗?

3 个答案:

答案 0 :(得分:19)

http://code.google.com/p/thrust/source/browse/examples/cuda/wrap_pointer.cu

Thrust为这个问题提供了一个很好的例子。

#include <thrust/device_ptr.h>
#include <thrust/fill.h>
#include <cuda.h>

int main(void)
{
    size_t N = 10;

    // obtain raw pointer to device memory
    int * raw_ptr;
    cudaMalloc((void **) &raw_ptr, N * sizeof(int));

    // wrap raw pointer with a device_ptr 
    thrust::device_ptr<int> dev_ptr = thrust::device_pointer_cast(raw_ptr);

    // use device_ptr in Thrust algorithms
    thrust::fill(dev_ptr, dev_ptr + N, (int) 0);    

    // access device memory transparently through device_ptr
    dev_ptr[0] = 1;

    // free memory
    cudaFree(raw_ptr);

    return 0;
}

从推力容器中获取原始指针已经由你自己解答了。

dbl2* ptrDVec = thrust::raw_pointer_cast(&d_vec[0]);

答案 1 :(得分:11)

您可以像标准容器一样初始化和填充推力向量,即通过迭代器:

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

在您的简单示例中,无需通过指针绕道而行,因为您可以直接复制其他容器。通常,如果您有一个指向数组开头的指针,那么如果您提供数组大小,则可以使用v3的版本。

答案 2 :(得分:3)

  

dbl2 * ptrDVec = thrust :: raw_pointer_cast(&amp; d_vec [0]);有没有办法从这个回到device_vector?

没有。虽然您应该能够重用初始向量变量。