Friday, April 12, 2013

CUDA Thrust: An example of conversion between device_vector, device_ptr, host_vector and raw pointer

 

   1: #pragma once 
   2:  
   3: #include <cuda_runtime.h>
   4: #include <thrust/device_vector.h>
   5: #include <thrust/device_ptr.h>
   6: #include "Particle.h"
   7: #include "ParticleSystem.h"
   8: #include <vector> 
   9:  
  10: // Template structure to pass to kernel
  11: template < typename T >
  12: struct KernelArray
  13: {    
  14:     T*  _array;    
  15:     int _size;
  16: }; 
  17:  
  18: // Function to convert device_vector to structure
  19: template < typename T >
  20: KernelArray< T > vecToKernelArr( thrust::device_vector< T >& dVec )
  21: {    
  22:     KernelArray< T > kArray;    
  23:     kArray._array = thrust::raw_pointer_cast( &dVec[0] );    
  24:     kArray._size  = ( int ) dVec.size();     
  25:     return kArray;
  26: }; 
  27:  
  28: // Function to convert a KernelArray to a thrust::device_vector
  29: template <typename T>
  30: thrust::device_vector<T> kernelArrToDevVec( KernelArray<T>& kArray )
  31: {  
  32:     thrust::device_ptr<T> dev_ptr = thrust::device_pointer_cast(kArray._array);
  33:     thrust::device_vector<T> dVec(dev_ptr, dev_ptr + kArray._size);
  34:     return dVec;
  35: } 
  36:  
  37: // Function to convert a KernelArray to a thrust::device_vector
  38: template <typename T>
  39: thrust::host_vector<T> kernelArrToHostVec( KernelArray<T>& kArray )
  40: {
  41:     thrust::device_ptr<T> dev_ptr = thrust::device_pointer_cast(kArray._array);
  42:     thrust::host_vector<T> hVec(dev_ptr, dev_ptr + kArray._size);
  43:     return hVec;
  44: } 
  45:  
  46: // Function to convert a KernelArray to a thrust::device_ptr
  47: template <typename T>
  48: thrust::device_ptr<T> kernelArrToDevPtr( KernelArray<T>& kArray )
  49: {
  50:     thrust::device_ptr<T> dev_ptr = thrust::device_pointer_cast(kArray._array);
  51:     return dev_ptr;
  52: }

No comments:

Post a Comment