c++ - OpenCL 和 std::vector<bool> 不兼容

标签 c++ c++11 vector boolean opencl

我有一个形成为 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 数组的快速赋值有什么建议吗?

谢谢!

最佳答案

两个问题。

  1. 实现可以(可选)优化 std::vector<bool>为了提高空间效率,也许可以通过将值打包到内存的各个位中来实现。这与 bool 数组的布局不匹配.

  2. 您不能像传递数组一样传递 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/

相关文章:

C++ 语法错误 - 无法识别问题

c++ - 在类里面使用模板的困惑

android - Android JNI 中的 OOM 错误

c++ - openssl API 的 G++ 编译错误

c++ - 如何判断在 Windows Mobile 6.5 中按下某个键 (c++)

c++ - 使用 getifaddrs 获取 CAN 接口(interface)数据包统计信息

c++ - 以自定义类作为键的 std::map 始终返回 1 的大小

c++ - 是否可以根据整数模板参数构造成员数组的元素?

c++ - 为什么 C++ 语言设计者不断重复使用关键字?

c++ - "Merge" vector 指针