我有一个形成为 std::vector 的 C++ 输入,我想将它传递到我的 OpenCL 内核(Nvidia 平台)。
但是当执行以下命令时,我一直遇到段错误:
queue.enqueueReadBuffer(dev_input, CL_TRUE, 0, sizeof(bool) * input.size(), &input);
因此,我尝试复制我的 std::vector<bool>
到 bool[]
一切都很完美。但是,将 vector 转换为 C 数组的常用方法 (&input[0], input.data())
根本不起作用。
您对 ReadBuffer 或对 C 数组的快速赋值有什么建议吗?
谢谢!
最佳答案
两个问题。
实现可以(可选)优化
std::vector<bool>
为了提高空间效率,也许可以通过将值打包到内存的各个位中来实现。这与bool
数组的布局不匹配.您不能像传递数组一样传递 vector 的地址。
std::vector<bool> input; queue.enqueueReadBuffer( dev_input, CL_TRUE, 0, sizeof(bool) * input.size(), &input); // ^^^^^^ wrong
如果你想将 vector 作为指针传递,你必须使用
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];
这就是为什么这是一个这么大的臭疣。
关于c++ - OpenCL 和 std::vector<bool> 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29115777/