2016-11-08 91 views
0

我試圖用Thrust創建設備仿函數,它將存儲對設備數據結構的引用作爲它們的狀態。函子然後會被傳入thrust::transform()和朋友。問題是我收到關於在仿函數的return聲明呼籲從設備碼中的主機功能錯誤:用Thrust創建和使用設備仿函數

// Compile with: 
// nvcc --std=c++11 device_functor.cu -o device_functor 

#include <thrust/host_vector.h> 
#include <thrust/device_vector.h> 
#include <thrust/complex.h> 

#include <iostream> 
#include <iomanip> 

struct my_functor { 
    my_functor(thrust::device_vector<unsigned char> &octets_) : 
     octets(octets_) {}; 

    __device__ 
    unsigned char operator()(int idx) const { 
     return octets[idx]; 
    } 
private: 
    thrust::device_vector<unsigned char> &octets; 
}; 


int main() { 
    thrust::device_vector<unsigned char> d_octets (4); 

    my_functor foo(d_octets); 

    d_octets[0] = 0x00; 
    d_octets[1] = 0x01; 
    d_octets[2] = 0x02; 
    d_octets[3] = 0x03; 

    std::cout << "0x" << std::hex << std::setfill('0') << std::setw(2) << static_cast <int> (foo(2)) << std::endl; 

    return 0; 
} 

其中一個在做這個正在訪問該位的最終目標在octets以各種方式的轉變,例如抓住第三組三位,第十組四位等,這一切都很容易,一旦我可以得到函子的工作。

+3

這有根本不可能工作,因爲函子內device_vector的機會。這是錯誤的根源,並且沒有辦法解決它。 – talonmies

+3

爲什麼不只是發佈一個答案,而不是用包含答案的「編輯1:」修改你的問題?或者,如果您願意,我可以將其標記爲其他推力問題的重複,詢問如何直接在設備代碼中使用推力矢量。 –

+0

將做出此修復並標記回答的問題。我沒有把它看作是一個重複的東西,因爲有一個問題是關於在設備代碼中創建推力矢量,而另一個則是在設備代碼中使用它們。 –

回答

1

重新寫仿函數正是如此通過@talonmies解決註釋出現這樣的伎倆:

struct my_functor { 
    my_functor(thrust::device_vector<unsigned char> &octets) : 
     octet_ptr(thrust::raw_pointer_cast(&octets[0])) {}; 

    __device__ 
    unsigned char operator()(int idx) const { 
     return *(octet_ptr + idx); 
    } 

private: 
    unsigned char *octet_ptr; 
};