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

mad*_*aze 19 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
Run Code Online (Sandbox Code Playgroud)

有人可以解释/指点我的例子吗?

pho*_*oad 20

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;
}
Run Code Online (Sandbox Code Playgroud)

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

dbl2* ptrDVec = thrust::raw_pointer_cast(&d_vec[0]);
Run Code Online (Sandbox Code Playgroud)


Ker*_* SB 12

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

#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
}
Run Code Online (Sandbox Code Playgroud)

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

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