參考https://lug.ustc.edu.cn/sites/qtguide/
今天看了一個介紹Qt串行化的介紹,感覺很受益,就記錄了下來。
串行化(Serialization)是計算機科學中的一個概念,它是指將對象存儲到介質(如文件、內存緩沖區等)中或是以二進制方式通過網絡傳輸。之后可以通過反串行化從這些連續的字節(byte)數據重新構建一個與原始對象狀態相同的對象,因此在特定情況下也可以說是得到一個副本,但並不是所有情況都這樣。
Qt 對這類組合數據的打包方法就叫串行化(Serializing),在 Qt 幫助文檔的索引里輸入關鍵詞 Serializing 就可以看到關於 Qt 串行化的幫助主題(Serializing Qt Data Types),除了 C++ 基本數值類型,Qt 還對大量自身的類對象做了串行化。串行化得到一個字節數組 QByteArray ,可以直接用於發送。Qt 串行化數據接收就是發送的逆過程,都是通過 QDataStream 流實現。
下面是一個簡單的實現
- //qtcodec.cpp
- #include <QDebug>
- #include <iostream>
- #include <QByteArray>
- #include <QDataStream>
- using namespace std;
- QByteArray TestSerialOut()
- {
- //數據
- int nVersion = 1;
- double dblValue = 125.78999;
- QString strName = QObject::tr("This an example.");
- //字節數組保存結果
- QByteArray baResult;
- //串行化的流
- QDataStream dsOut(&baResult, QIODevice::ReadWrite); //做輸出,構造函數用指針
- //設置Qt串行化版本
- dsOut.setVersion(QDataStream::Qt_5_0);//使用Qt 5.0 版本流
- //串行化輸出
- dsOut<<nVersion<<dblValue<<strName;
- //顯示長度
- qDebug()<<baResult.length()<<"\t"<<qstrlen(baResult.data());
- //返回對象
- return baResult;
- }
- void TestSerialIn(const QByteArray& baIn)
- {
- //輸入流
- QDataStream dsIn(baIn); //只讀的流,構造函數用常量引用
- //設置Qt串行化版本
- dsIn.setVersion(QDataStream::Qt_5_0);//使用Qt 5.0 版本流
- //變量
- int nVersion;
- double dblValue;
- QString strName;
- //串行化輸入
- dsIn>>nVersion>>dblValue>>strName;
- //打印
- qDebug()<<nVersion;
- qDebug()<<fixed<<dblValue;
- qDebug()<<strName;
- }
- int main()
- {
- QByteArray ba = TestSerialOut();
- TestSerialIn(ba);
- return 0;
- }
http://blog.csdn.net/guoqianqian5812/article/details/50810154