从thrust::device_vector到原始指针再返回

From thrust::device_vector to raw pointer and back?

本文关键字:原始 指针 返回 vector thrust device      更新时间:2023-10-16

我明白如何从矢量到原始指针,但我跳过了如何向后走的节拍。

// 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
谁能给我举个例子?

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]);

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

#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的版本。

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

没有。尽管您应该能够重用初始向量变量