2011-10-06 13 views
13

Capisco come passare da un vettore a un puntatore crudo, ma sto saltando un battito su come andare indietro.Da thrust :: device_vector a puntatore e ritorno raw?

// 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 

Qualcuno può spiegare/indicarmi un esempio?

risposta

9

si inizializza e popolare vettori di spinta proprio come contenitori standard, vale a dire tramite iteratori:

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

Nel vostro semplice esempio non c'è bisogno di andare alla deviazione tramite puntatori, come si può semplicemente copiare direttamente l'altro contenitore. In generale, se si dispone di un puntatore all'inizio di un array, è possibile utilizzare la versione per v3 se si specifica la dimensione dell'array.

+0

così appena da un puntatore, senza la lunghezza non c'è modo di tornare a un device_vector? – madmaze

+3

dbl2 * ptrDVec = thrust :: raw_pointer_cast (& d_vec [0]); c'è un modo per tornare a un device_vector da questo? – madmaze

+0

Cosa intendi per "tornare indietro" - non è già un puntatore del dispositivo? Di cosa hai bisogno esattamente? –

3

dbl2 * ptrDVec = thrust :: raw_pointer_cast (& d_vec [0]); c'è un modo per tornare a un device_vector da questo?

Non c'è. Anche se dovresti essere in grado di riutilizzare la variabile vettoriale iniziale.

18

http://code.google.com/p/thrust/source/browse/examples/cuda/wrap_pointer.cu

Thrust fornisce un buon esempio per questa domanda.

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

E ricevendo il puntatore grezzo dai contenitori di spinta è come risposta già da soli ..

dbl2* ptrDVec = thrust::raw_pointer_cast(&d_vec[0]); 
Problemi correlati