Important: Please read the Qt Code of Conduct -

How to safely get data from QBytearray * into unsigned char * const (openssl related)

  • My goal is to safely pass QBytearray contents to openssl function for which I wrote wrapper. It requires unsigned char array as parameter. So far I'm here:

    foo(QByteArray *  _data);
     unsigned char *data = new unsigned char[_data->size()];
     data=reinterpret_cast<unsigned char*>(data->data());

    I would like to protect _data from accidental change and use unsigned char * const in declaration of data.

    • I could pass QByteArray as value. Would system make deep copy immediately or after I tried to modify it ? How to best protect it from accidental modification inside in this case ?
    • I can't picture in my head putting together *const = new and assigning value in one line. Can you please help me out on this one ?

    Thank you.

  • Lifetime Qt Champion Why not just:

    foo(QByteArray *  _data);
         const unsigned char *data = reinterpret_cast<const unsigned char*>(_data->constData());

    No need to allocate any new memory.

    In your version you do not copy the data from QByteArray to newly allocated array, as this assignment just assigns a new pointer value to data:

    data=reinterpret_cast<unsigned char*>(data->data());

  • Hi @levi-pl,

    I'm not sure I understand your question fully, but it sounds like you want to use QByteArray::constData().

    const char * const data = _data.constData();

    And if you specifically want unsigned chars, then you can cast like so:

    const uchar * const data = reinterpret_cast<const uchar *>(_data.constData());

    Is that what you were asking?

  • @jsulm beat me to it :)

  • @Paul-Colby @jsulm :

    I'm still switching my brain to think in C/C++. One step closer. Thank you guys. Confirmed kill.

Log in to reply