5
QByteArray inArray = " ... ";
unsigned char *in = convert1(inArray);
unsigned char *out;
someFunction(in, out);
QByteArray outArray = convert2(out);

the question is how can I correctly make these conversions (convert1 and convert2). I cannot change someFunction(unsigned char *, unsigned char *), but I have to work with QByteArray here.

Eddie
  • 1,436
  • 5
  • 24
  • 42

2 Answers2

7

Qt has really great docs, you should use them.

If someFunction doesn't modify or store pointer to in data you can use this:

QByteArray inArray = " ... ";
unsigned char *out;
someFunction((unsigned char*)(inArray.data()), out);
QByteArray outArray((char*)out);

Otherwise you have to make a deep copy of the char* returned by QByteArray::data() (see the docs for code snippet).

chalup
  • 8,358
  • 3
  • 33
  • 38
  • `QByteArray outArray = QByteArray::fromRawData(out, strlen(out));` If you are not going to use `out`. – graphite Jan 20 '12 at 11:11
  • If I use fromRawData, I get "invalid conversion from 'unsigned char*' to 'const char*'". so I tried QByteArray::fromRawData(reinterpret_cast(out), part.length()). – Eddie Jan 20 '12 at 11:16
  • The solution by chalup seems to be good and I tried it before, but I got errors with it. Apparently the case is in something else. – Eddie Jan 20 '12 at 11:25
0

if someFunction takes a const char* args then just use ConstData() or data() in QByteArray class.

if you need a char*, you can then use strdup(). This method is doing this

char *strdup (const char *s) {
    char *d = malloc (strlen (s) + 1);   // Space for length plus nul
    if (d == NULL) return NULL;          // No memory
    strcpy (d,s);                        // Copy the characters
    return d;                            // Return the new string
}

more info here: strdup() - what does it do in C?

Community
  • 1
  • 1
kiriloff
  • 25,609
  • 37
  • 148
  • 229