Search code examples
cudathrust

Wrapping Thrust Device Vectors in a struct?


I am implementing a math algorithm that requires keeping ~15 different vectors of floats around. I'd like to wrap all of these device vectors into a struct

typedef struct {
  thrust::device_vector<float> ...
} data;

and pass this struct around to different functions. Is it possible to have such a wrapping? When I try to initialize one such struct

data* mydata = (data*) malloc(sizeof(struct data)); 

I receive this error

error: typedef "data" may not be used in an elaborated type specifier

Also, I'm suspicious about mallocing a block of memory of size data when none of its contents reside in host memory


Solution

  • As mentioned in the comments, the original error described in the title is not thrust related, but due to use of struct data, when data is already typedef'ed.

    In response to the additional question posed in the comments, I merely was trying to state that I had not fully thought about the ramifications of using thrust::device_vector<> inside a struct. When I said maybe consider using thrust::device_ptr<> instead, I had in mind something like this, which seems to work for me:

    #include <stdio.h>
    #include <thrust/host_vector.h>
    #include <thrust/device_vector.h>
    #include <thrust/device_ptr.h>
    #include <thrust/sequence.h>
    #include <thrust/transform.h>
    #include <thrust/functional.h>
    
    #define N 10
    
    typedef struct {
      thrust::device_ptr<float> dp1;
      thrust::device_ptr<float> dp2;
      int i;
    } data;
    
    
    int main(){
    
      thrust::negate<int> op;
    
      data *mydata = (data *)malloc(sizeof(data));
      thrust::host_vector<float> h1(N);
      thrust::sequence(h1.begin(), h1.end());
      thrust::device_vector<float> d1=h1;
      mydata->dp1=d1.data();
      mydata->dp1[0]=mydata->dp1[N-1];
    
      thrust::transform(mydata->dp1, mydata->dp1 + N, mydata->dp1, op); // in-place transformation
    
      thrust::copy(d1.begin(), d1.end(), h1.begin());
      for (int i=0; i<N; i++)
        printf("h1[%d] = %f\n", i, h1[i]);
    
      return 0;
    }
    

    Having said that, the original method of using device_vector inside a struct may work, I just don't know and have not explored it.