C++ 将 unsigned char[10] 转换为 QBytearray;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15337180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:17:14  来源:igfitidea点击:

Convert unsigned char[10] to QBytearray;

c++qtconverterunsigned-charqbytearray

提问by SamuelNLP

I've seen a lot o questions around this, but so far none worked for me.

我已经看到很多关于这个的问题,但到目前为止没有一个对我有用。

I've tried the 2 most common answers but I get the same error.

我已经尝试了 2 个最常见的答案,但我得到了同样的错误。

being but an unsigned char buf[10];

只是一个 unsigned char buf[10];

this,

这个,

QByteArray databuf;
databuf = QByteArray::fromRawData(buf, 10); 

or this,

或这个,

QByteArray databuf;
databuf = QByteArray(buf, 10);

got me the same error,

给我同样的错误,

error: invalid conversion from 'unsigned char*' to 'const char*' [-fpermissive]

error: invalid conversion from 'unsigned char*' to 'const char*' [-fpermissive]

any advice?

有什么建议吗?

thank you

谢谢你

回答by hyde

It's just signedness issue, so this should work:

这只是签名问题,所以这应该有效:

databuf = QByteArray(reinterpret_cast<char*>(buf), 10);

Or with legacy C-style cast:

或者使用传统的 C 风格强制转换:

databuf = QByteArray((char*)buf, 10);

(Here's one of many many discussions about which you should use.)

这是您应该使用的众多讨论之一。

Easier alternative is to remove unsignedfrom declaration of buf, if you don't need it there for some other reason.

更简单的替代方法是unsigned从 声明中删除buf,如果由于其他原因不需要它。

Note, that if you use that fromRawDatamethod, it does not copy the bytes, so better be sure bufwon't go out of scope too soon. If unsure, do not use it...

请注意,如果您使用该fromRawData方法,它不会复制字节,因此最好确保buf不会过早超出范围。如果不确定,请不要使用它...

回答by Joseph Mansfield

As it says, the argument passed to fromRawDatashould be a const char*, not an unsigned char*. You could make your array be an array of const char:

正如它所说,传递给的参数fromRawData应该是 a const char*,而不是 an unsigned char*。你可以让你的数组是一个数组const char

const char buf[10];

The array can be converted to a pointer to its first element which will a const char*, exacly as fromRawDataexpects.

该数组可以转换为指向其第一个元素的指针const char*,正如fromRawData预期的那样,该元素将 a 。