9

I am trying to create QByteArray from std::vector.. I tried;

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

However it gives error;

error: invalid cast from type 'std::vector<unsigned char, std::allocator<unsigned char> >' to type 'const char'
goGud
  • 4,163
  • 11
  • 39
  • 63

1 Answers1

19

You need to cast buf.data() instead of buf:

QByteArray* img = new QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());
m.s.
  • 16,063
  • 7
  • 53
  • 88
  • 4
    Note `.data()` is only available in C++11 and later. If your compiler doesn't support this, use `&buf[0]`. – Saul Jun 29 '15 at 11:00
  • when I use buf.data() it says `error: cast from 'unsigned char*' to 'const char' loses precision` – goGud Jun 29 '15 at 11:39
  • ohh.. my mistake, I didnt use char pointer.. thank you very much – goGud Jun 29 '15 at 11:40
  • I personally do avoid new and delete wherever I can. You can do on modern compilers like this: [auto img = QByteArray(reinterpret_cast(buf.data()), buf.size());] – akira hinoshiro May 27 '20 at 07:55