QByteArray convert to/from unsigned char *

匿名 (未验证) 提交于 2019-12-03 09:18:39

问题:

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.

回答1:

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).



回答2:

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?



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!