Thrust 从推力::设备_向量到原始指针,再返回?

Thrust 从推力::设备_向量到原始指针,再返回?,thrust,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 = &

我知道如何从一个向量到一个原始指针,但我跳过了如何向后走的节拍

// 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
//我们的宿主向量
推力:主向量hVec;
//假设我们把数据放在这里
//获取一个设备向量
推力:装置矢量dVec=hVec;
//获取设备ptr
推力::设备_ptrdevptr=&d_vec[0];
//现在我如何回到设备_向量?
推力:设备向量dVec2=devPtr;//出错
推力:设备向量dVec2(devPtr);//出错

有人能给我解释一下/给我举个例子吗?

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

#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
}
#包括
#包括
int main()
{
推力::设备_向量v1(10);//创建一个大小为10的向量
推力::设备_ptrdp=v1.data();//或&v1[0]
推力::设备_向量v2(v1);//从副本
推力::设备向量v3(dp,dp+10);//来自迭代器范围
推力::设备向量v4(v1.begin(),v1.end());//来自迭代器范围
}
在您的简单示例中,不需要通过指针绕道而行,因为您可以直接复制另一个容器。通常,如果有指向数组开头的指针,如果提供数组大小,则可以使用
v3
的版本


dbl2*ptrDVec=推力::原始指针投射(&d_vec[0]);有没有办法从这里回到设备向量

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

推力为这个问题提供了一个很好的例子

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

因此,仅仅从一个指针开始,如果没有长度,就无法返回到一个设备向量?db2*ptrDVec=推力::raw_pointer_cast(&d_vec[0]);有没有办法从这里返回到设备向量?你说的“返回”是什么意思?它不是已经是设备指针了吗?你到底需要什么?我需要能够保存一个指向设备向量的指针/引用(假设我有dVec1和dVec2),然后做一些事情,做一些条件,最后我想将指向dVec1或dVec2的指针转换为设备向量int-dVec3。。这个想法是通过引用来传递dVec,然后在某个点将其解绑,并再次将其用作设备向量
dbl2* ptrDVec = thrust::raw_pointer_cast(&d_vec[0]);