CUDA-Thrust(2)--野指针转换
1.野指针:
前两篇博文定义的向量都是在device_vector和host_vector向量空间,如果我们定义一个
像int* raw_ptr的野指针,怎样实现数据间的传递呢?Thrust提供给我们一些函数帮助我们解决
这样的问题。thrust::raw_pointer_cast和thrust::device_ptr<int> dev_ptr(raw_ptr)。
2.代码:
接下来的例子就是为展示,野指针在device_vector在空间中的操作:
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <stdio.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/copy.h> #include <thrust/fill.h> #include <thrust/sequence.h> #include <iostream> int main(void) { int N = 10; //define H on host thrust::host_vector<int>H(N); //initialize H thrust::sequence(H.begin(), H.end(), 0); //show the sequence H std::cout << "show the original H" << std::endl; for (int i = 0; i < H.size(); ++i) std::cout << "H[" << i << "]=" << H[i] << std::endl; // 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(raw_ptr); //copy the elements from host_vector to device_vector thrust::copy(H.begin(), H.end(), dev_ptr); //extract raw pointer from device_ptr raw_ptr = thrust::raw_pointer_cast(dev_ptr); int *test = new int[N]; cudaMemcpy(test, raw_ptr, N * sizeof(int), cudaMemcpyDeviceToHost); //show the sequence test std::cout << "show the original test" << std::endl; for (int i = 0; i < H.size(); ++i) std::cout << "test[" << i << "]=" << test[i] << std::endl; delete(test); cudaFree(raw_ptr); return 0; }