2013-07-12 40 views
1

我有其可以是C++的數據結構和CUDA

struct type1{ double a,b,c;} 

或結構也可以是

struct type2{ double a,b,c,d,e;} 

在CUDA代碼我的主機功能我有成纔像

void compute(){ 
     // some code 
     // data on devices (up to 10) 
     type *xxx[10]; // this is where i want either type1 or type2 structures 
         // the "type" is not known at compile time but i want to 
         // determine at runtime based on some input variable. this 
         // part is not real code rather this is what i want to achive. 

     int DevUsed; // some code to give value to int DevUsed 

     for(int idev=0;idev<DevUsed;idev++){ 

      // set cuda device 

      if (cudaMalloc(&xxx[iDev], sizeof(type)) != cudaSuccess) 
      // print error message; 
      cudaMemcpy(xxx[iDev], pIF1, sizeof(type), cudaMemcpyHostToDevice); 

      function2<<<grid, block>>>(xxx[iDev]); // where function2 is the kernel 
     } 
    } 

我的問題是什麼是使用類型爲「type * xxx [10];」的泛型代碼在type1和type2數據結構之間進行選擇的方法。

+0

這兩類內核模板嘗試使用'typeid'如果它運行時僅 – Twifty

+2

模板? http://www.cplusplus.com/doc/tutorial/templates/ – KiaMorot

+0

你正在試圖聲明一個'10'指針的'數組'指向編譯時不知道的'type'的數據嗎?我不確定你可以用模板來做到這一點,因爲模板函數,結構或類需要在編譯時實例化。可能最好的辦法是聲明一個指向'void'的數組?但我有一種感覺,你應該在編譯時瞭解所有類型。 – JackOLantern

回答

1

C++模板是針對這種情況而設計的。

template <class T> 
void compute(){ 
    // some code 
    // data on devices (up to 10) 
    T xxx[10]; // this is where i want either type1 or type2 structures 
        // the "type" is not known at compile time but i want to 
        // determine at runtime based on some input variable. this 
        // part is not real code rather this is what i want to achive. 

    int DevUsed; // some code to give value to int DevUsed 

    for(int idev=0;idev<DevUsed;idev++){ 

     // set cuda device 

     if (cudaMalloc(&xxx[iDev], sizeof(T)) != cudaSuccess) 
     // print error message; 
     cudaMemcpy(xxx[iDev], pIF1, sizeof(T), cudaMemcpyHostToDevice); 

     function2<<<grid, block>>>(xxx[iDev]); // where function2 is the kernel 
    } 
} 

請注意,您還需要像

template <class T> 
__global__ void function2(T x) 
{ 
    //.... 
} 
+0

但與模板,我認爲你應該在編譯時明確實例化函數。當用戶聲稱僅在運行時才知道類型「T」時,它有多可能? – JackOLantern

+0

猜他應該實現這兩種類型的代碼,並在運行時選擇一個... – KiaMorot