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
Convert unsigned char[10] to QBytearray;
提问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 unsigned
from declaration of buf
, if you don't need it there for some other reason.
更简单的替代方法是unsigned
从 声明中删除buf
,如果由于其他原因不需要它。
Note, that if you use that fromRawData
method, it does not copy the bytes, so better be sure buf
won'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 fromRawData
should 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 fromRawData
expects.
该数组可以转换为指向其第一个元素的指针const char*
,正如fromRawData
预期的那样,该元素将 a 。