[英]OpenCL and std::vector<bool> incompatibility
我有一個以std :: vector形式形成的C ++輸入,我想將其傳遞給我的OpenCL內核(Nvidia平台)。
但是執行以下命令時,我總是遇到分段錯誤:
queue.enqueueReadBuffer(dev_input, CL_TRUE, 0, sizeof(bool) * input.size(), &input);
因此,我嘗試將std::vector<bool>
復制到bool[]
並且一切正常。 但是,將向量轉換為C數組的常用方法( &input[0], input.data())
根本不起作用。
您對ReadBuffer或對C數組的快速分配有什么建議嗎?
謝謝!
兩個問題。
實現可以(可選)將std::vector<bool>
優化為更節省空間,也許是通過將值打包到內存的各個位中來實現的。 這將與bool
數組的布局不匹配。
您不能像將向量當作數組一樣傳遞向量的地址。
std::vector<bool> input; queue.enqueueReadBuffer( dev_input, CL_TRUE, 0, sizeof(bool) * input.size(), &input); // ^^^^^^ wrong
如果要傳遞向量作為指針,則必須使用input.data()
或類似&input[0]
東西。 這些方法不起作用的原因是std::vector<bool>
旨在防止這種情況發生,因為可能會優化實現(請參見第1點)。
從本質上講,這是C ++庫中的“缺陷”,已經隨着時間的流逝而產生。
解決這個問題很痛苦。
// One way to do things...
struct Bool { bool value; }
std::vector<Bool> input;
// Another way to do things...
// (You have to choose the right type here, it depends
// on your platform)
std::vector<int> input;
// Yet another way...
bool *input = new bool[N];
這就是為什么這是一個很大的疣。
一種可能性是使用Boost.Compute提供的copy()
算法。
基本上,您可以執行以下操作:
// vector of bools on the host
std::vector<bool> host_vec = { ... };
// vector of bools on the device (each represented with a uchar)
boost::compute::vector<uchar_> gpu_vec(host_vec.size(), ctx);
// copy bool values on host to the device
boost::compute::copy(host_vec.begin(), host_vec.end(), gpu_vec.begin(), queue);
Boost.Compute將負責將數據正確復制到計算設備。
要添加的另一件事:
OpenCL內核中的bool
類型不能保證與任何主機端類型匹配。 通常,應避免在主機設備互連中使用布爾類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.