我想將QVector序列化成char *數組。我通過以下代碼執行此操作:QDataStream在外部存儲器上?
QVector<int> in;
...
QByteArray bytes;
QDataStream stream(&bytes, QIODevice::WriteOnly);
stream << in;
std::copy(bytes.constData(), bytes.constData() + bytes.size(), out);
我保證out
足夠大。由於這段代碼經常被調用,所以我想避免這種不必要的std::copy
操作,並且使QByteArray
或QDataStream
可以在由out
指向的預先分配的用戶內存上工作。那可能嗎?任何想法?
UPDATE:的QByteArray :: fromRawData()不匹配的需求導致它不允許改變字符*緩衝創建它上,換言之,上的QByteArray這種第一修改執行深層副本創建實例。 正如他們所說。 這確保原始數據數組本身永遠不會被QByteArray修改。
解決方案:@skyhisi提出的解決方案完全符合我的需求。完整的代碼如下。
SimpleBuffer.hpp
#pragma once #include <QtCore/QIODevice> class SimpleBuffer : public QIODevice { Q_OBJECT Q_DISABLE_COPY(SimpleBuffer) public: SimpleBuffer(char* const begin, const char* const end) : _begin(begin), _end(end){} virtual bool atEnd() const { return _end == _begin; } virtual bool isSequential() const { return true; } protected: virtual qint64 readData(char*, qint64) { return -1; } virtual qint64 writeData(const char* const data, const qint64 maxSize) { const qint64 space = _end - _begin; const qint64 toWrite = qMin(maxSize, space); memcpy(_begin, data, size_t(toWrite)); _begin += toWrite; return toWrite; } private: char* _begin; const char* const _end; };
的main.cpp
#include "SimpleBuffer.hpp" #include <QtCore/QVector> #include <QtCore/QDataStream> #include <QtCore/QByteArray> int main(int, char**) { QVector<int> src; src << 3 << 7 << 13 << 42 << 100500; const size_t dataSize = sizeof(quint32) + src.size() * sizeof(int); char* const data = new char[dataSize]; // prepare stream and write out the src vector { SimpleBuffer simpleBuffer(data, data + dataSize); simpleBuffer.open(QIODevice::WriteOnly); QDataStream os(&simpleBuffer); os << src; } // read vector with QByteArray QVector<int> dst; { const QByteArray byteArray = QByteArray::fromRawData((char*)data, dataSize); QDataStream is(byteArray); is >> dst; } delete [] data; // check we've read exactly what we wrote Q_ASSERT(src == dst); return 0; }
它像一個魅力,感謝你! – prokher 2012-04-30 17:25:59
將您的解決方案添加到原始郵件。 – prokher 2012-04-30 17:46:05