QT5 QByteArray Struct convert
时间: 2023-08-08 20:08:00 浏览: 110
To convert a `QByteArray` to a `struct`, you can use a combination of `QDataStream` and `memcpy`.
First, define your `struct` with the desired fields and their types. For example:
```cpp
struct MyStruct {
int id;
QByteArray name;
double value;
};
```
Then, to convert a `QByteArray` to this `struct`, you can use the following code:
```cpp
QByteArray byteArray = ... // your QByteArray
MyStruct myStruct;
QDataStream stream(&byteArray, QIODevice::ReadOnly);
stream.readRawData((char*) &myStruct.id, sizeof(myStruct.id));
stream >> myStruct.name;
stream.readRawData((char*) &myStruct.value, sizeof(myStruct.value));
```
This reads each field from the `QByteArray` using `QDataStream`, and uses `memcpy` to copy the data into the corresponding field in the `struct`.
Similarly, to convert a `struct` to a `QByteArray`, you can use the following code:
```cpp
MyStruct myStruct = ... // your struct
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream.writeRawData((char*) &myStruct.id, sizeof(myStruct.id));
stream << myStruct.name;
stream.writeRawData((char*) &myStruct.value, sizeof(myStruct.value));
```
This writes each field of the `struct` to the `QByteArray` using `QDataStream`, and the resulting `QByteArray` can be sent or stored as needed.
阅读全文