2013-03-28 31 views
2

我試圖在CUDA中使用我的C++類。在CUDA中有選擇地編譯頭文件和類函數

我有一類這樣:

#include<string> 
#include<stdlib.h> 

class exampleClass{ 
int i; 
__host__ __device__ exampleClass(int _i):i(_i){}; 
__host__ __device__ void increment(){i++;} 
__host__ __device__ string outputMessage(return itoa(i);} 

}; 

我已經在.CU文件中設置此並設置編譯CUDA C/C++

這種失敗,NVCC編譯因爲CUDA不有字符串。

我想要做的是做類似保留CUDA唯一功能:

#ifndef __CUDA_ARCH__ 
    #include<string> 
#endif 
    #include<stdlib.h> 

    class exampleClass{ 
    int i; 
    __host__ __device__ exampleClass(int _i):i(_i){}; 
    __host__ __device__ void increment(){i++;} 
#ifndef __CUDA_ARCH__ 
    string outputMessage(return itoa(i);} 
#endif 

    }; 

但我知道這是行不通......至少,它不是爲我工作。 nvcc不喜歡字符串包含,也不顯示需要字符串類型的函數。

道歉,如果這個例子不是一流的。總之,我想要做的是在CUDA上具有可執行的核心類成員,同時保持在主機端進行分析和輸出的花哨主機操作的能力。

更新:我的最終目標是創建一個基類,其中包含幾個指向多個多態類的指針類型。這個基類本身是可以推導出來的。我認爲這在CUDA5.0中是可行的。我錯了嗎?

+0

我用nvcc使用stl類,如字符串或向量,沒有問題。你當然不能將字符串發送到內核,或者在內核中使用字符串函數,但是看起來不像你想要做的那樣......你應該只能刪除「__device__」裝飾。 – IdeaHat

+0

MadScienceDreams對我的問題的回答是正確的。然而,這個問題的根本問題在這裏找到了它的解決方案:http://stackoverflow.com/questions/5994005/cuda-external-calls-not-supported – PaulD

+1

更具體地說,您需要在CUDA C中包含-dc標誌/ C++編譯器允許多個cu文件之間的鏈接。 – PaulD

回答

2

下面的代碼生成,雖然我沒有運行它:

class exampleClass{ 
int i; 
public: 
__host__ __device__ exampleClass(int _i):i(_i){}; 
__host__ __device__ void increment(){i++;} 

__host__ string outputMessage(){ return "asdf";} 


}; 

__global__ void testkernel (      
    exampleClass *a, 
    int IH, int IW) 
{ 
    const int i = IMUL(blockIdx.x, blockDim.x) + threadIdx.x; 
    const int j = IMUL(blockIdx.y, blockDim.y) + threadIdx.y; 


    if (i<IW && j<IH) 
    { 
     const int i_idx = i + IMUL(j, IW); 
     exampleClass* ptr = a+i_idx; 
     ptr->increment(); 
    } 
} 

__host__ void test_function(exampleClass *a, 
    int IH, int IW) 
{ 
    for (int i = 0; i < IW; i++) 
     for (int j = 0; j < IH; j++) 
     { 
      const int i_idx = i + j*IW; 
      exampleClass* ptr = a+i_idx; 
      cout << ptr->outputMessage(); 
     } 
} 

請注意,你必須把階級從設備移動到承載此內存「工作」正常。如果您嘗試對類進行任何操作(例如多態),這可能會炸燬。

+0

我認爲CUDA5.0允許多態嗎?我的「exampleClass」是一個包含多個派生類的基類。而且,exampleClass包含了保存多態類的幾個點。 – PaulD

+0

@PaulD。呵呵,這是從4.0開始的一個很酷的變化。 CUDA是少數幾款似乎每年都會添加漂亮功能的軟件包之一!這些類的VTable必須同時引用'__host__'和'__device__'函數指針,所以類的大小會變得非常快。請注意,虛擬繼承仍然不受支持。 – IdeaHat

+0

我不熟悉VTable ......我不僅僅是一個自我教導。你可以解釋一下或發佈鏈接?同時,nVidia網站也表示,自Toolkit 4.0以來,虛擬繼承得到了支持。 https://developer.nvidia.com/cuda-toolkit-40 – PaulD