我假設你的輸入數據是二進制(不是文本),並且你想從中提取二進制數據塊。所有這些都不需要複製輸入數據。
您可以結合boost::iostreams::basic_array_source
和boost::iostreams::stream_buffer
(從Boost.Iostreams)與boost::archive::binary_iarchive
(從Boost.Serialization),以能夠使用便捷的提取>>運營商讀取二進制數據塊。
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_iarchive.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> buffer(dataPtr, sizeof(data));
boost::archive::binary_iarchive archive(buffer, boost::archive::no_header);
uint16_t word1, word2;
archive >> word1 >> word2;
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
隨着AMD64 GCC 4.4.1,它輸出:
1234,5678
Boost.Serialization是非常強大的,並且知道如何連載所有的基本類型,字符串,甚至STL容器。你可以很容易地讓你的類型可序列化。請參閱文檔。隱藏在Boost.Serialization源代碼中的某個地方是一個便攜式二進制歸檔文件的例子,它知道如何爲您的機器的字節順序執行適當的交換。這對你也可能有用。
如果您不需要Boost.Serialization的裝飾性,並很高興在FREAD讀取二進制數據() - 時尚型,你可以在一個更簡單的方式使用basic_array_source
:
#include <stdint.h>
#include <iostream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
int main()
{
uint16_t data[] = {1234, 5678};
char* dataPtr = (char*)&data;
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream<Device> stream(dataPtr, sizeof(data));
uint16_t word1, word2;
stream.read((char*)&word1, sizeof(word1));
stream.read((char*)&word2, sizeof(word2));
std::cout << word1 << "," << word2 << std::endl;
return 0;
}
我用這個程序得到相同的輸出。
什麼版本的MSVC? > 6,我希望。 ;) – 2010-01-17 06:15:24
MSVC 9.0又名2008 – 2010-01-17 06:21:16
我認爲你的解決方案很好。 :) http://stackoverflow.com/questions/1448467/initializing-ac-stdistringstream-from-an-in-memory-buffer/1449527#1449527 – 2010-01-17 10:55:28