c++ - 从 Thrust::device_vector 到原始指针并返回?

标签 c++ cuda thrust

我了解如何从 vector 到原始指针,但我跳过了如何向后的节拍。

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

关于c++ - 从 Thrust::device_vector 到原始指针并返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7678995/

相关文章:

python - CuPy 不适用于带有 CUDA 9.0 的 Ubuntu 18.04

c++ - 使用 thrust::for_each() 调用实现 CUDA 流时访问结构的结果

c++ - 如何在将由 Thrust 在 GPU 上使用的仿函数中使用 boost.compute 函数?

c++ - 如何处理警告:cast to int* from smaller integer type int

cuda:cpu和gpu之间的不同答案减少

visual-studio-2010 - Fermi GPU 错误 : identifier "atomicAdd" is undefined under visual studio 2010 & cuda 4. 2

c++ - CUDA 推力性能

c++ - Visual Studio 2012 附加库包括来自项目属性

c++ - 我可以使用 opencv 函数,例如 cv::multiply 和 std::vector<cv::Mat> 作为输入和输出参数吗?

c++ - 任务在删除其中一个迭代对象时会导致段错误