【问题标题】:How to convert std::vector<uint8_t> to QByteArray?如何将 std::vector<uint8_t> 转换为 QByteArray?
【发布时间】:2015-09-15 19:24:39
【问题描述】:

我正在尝试从 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'

【问题讨论】:

    标签: c++ qt vector qbytearray


    【解决方案1】:

    您需要投射buf.data() 而不是buf

    QByteArray* img = new QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());
    

    【讨论】:

    • 注意 .data() 仅在 C++11 及更高版本中可用。如果您的编译器不支持此功能,请使用&amp;buf[0]
    • 当我使用 buf.data() 它说error: cast from 'unsigned char*' to 'const char' loses precision
    • 哦..我错了,我没有使用char指针..非常感谢
    • 我个人尽量避免新建和删除。您可以在现代编译器上这样做: [auto img = QByteArray(reinterpret_cast(buf.data()), buf.size());]
    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2014-02-19
    • 2021-07-11
    • 2013-09-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    相关资源
    最近更新 更多