0

want to convert a QString to GBytes (glib)

I tried the following by converting the QString to GByteArray and than freeing it to GBytes

extern "C" {
#include <glib.h>
};
#include <QString>
#include <QApplication>

int main(int argc, char *argv[])
{

    QApplication app(argc, argv);

QString mylongstring = "HELLO_WORLD";

GByteArray *barr;
barr = g_byte_array_new ();

for (int i = 0; i < mylongstring.toLocal8Bit().count(); i++)
{
     guint8 *charAt = (guint8*)mylongstring.at(i); //cant convert qchar to uint -> already crashes

    g_byte_array_append (barr, (guint8*) charAt, 1); 
}
GBytes *gbytes = g_byte_array_free_to_bytes(barr); //should contain the (guint8*) data of mylongstring

    return app.exec();
}
Gtk Fan
  • 45
  • 6

2 Answers2

1

Why not take the GByteArray from the QByteArray ? whats the purpose of the loop ?

I think your cast is causing the issue because it does not allocate enough bytes, check this : https://doc.qt.io/qt-5/qbytearray.html#data

rewriting your code, by taking GByteArray from QByteArray data() seems safer ..

QByteArray _string2BA = mylongstring.toLocal8Bit();
char *data = new char[_string2BA.size() + 1];
strcpy(data, _string2BA.data());
GByteArray *barr;
barr = g_byte_array_new ();
barr = (GByteArray*)data;

GBytes *gbytes = g_byte_array_free_to_bytes(barr); //should contain the (guint8*) data of mylongstring
Mohammad Kanan
  • 4,452
  • 10
  • 23
  • 47
0

The lines you have to change:

guint8 *charAt = (guint8*)mylongstring.at(i);
g_byte_array_append (barr, (guint8*) charAt, 1);

to

guint8 charAt = (guint8)mylongstring.toLocal8Bit().at(i);
g_byte_array_append (barr, &charAt, 1);

But consider this.

Returns the local 8-bit representation of the string as a QByteArray. The returned byte array is undefined if the string contains characters not supported by the local 8-bit encoding. source

Memos Electron
  • 660
  • 5
  • 26