如何将std::vector<uint8_t>转换为QByteArray?

9

我正在尝试从std::vector创建QByteArray。 我尝试过以下方法;

std::vector<uint8_t> buf;
QByteArray img = new QByteArray(reinterpret_cast<const char>(buf), buf.size());

然而,它出现了错误;
error: invalid cast from type 'std::vector<unsigned char, std::allocator<unsigned char> >' to type 'const char'
1个回答

19
您需要将buf替换为buf.data()进行转换:
QByteArray* img = new QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());

4
注意,.data() 只在 C++11 及其以后的版本中可用。如果你的编译器不支持这个函数,可以使用 &buf[0] - Saul
当我使用buf.data()时,会出现“error: cast from 'unsigned char*' to 'const char' loses precision”错误。 - goGud
哦..我的错误,我没有使用字符指针..非常感谢你。 - goGud
我个人尽可能避免使用 new 和 delete。你可以在现代编译器中像这样做: [auto img = QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());] - akira hinoshiro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接