繁体   English   中英

二进制读/写std :: stringstream

[英]Binary read/write to std::stringstream

我有以下代码尝试读取/写入unsigned int和std :: wstring到std :: stringstream。

#include <memory>
#include <iostream>
#include <vector>
#include <sstream>

class SerializationException : public std::runtime_error
{
public:
    SerializationException( const char* msg ) : std::runtime_error( msg ) { }
};

class Serialization
{
public:
    static void Write( std::ostream& stream, const std::wstring& item )
    {
        Write(stream, eStdWString);
        Write(stream, item.length());
        stream.write( reinterpret_cast< const char* >( item.c_str() ), item.length() );
    }

    static std::wstring ReadWString( std::istream& stream )
    {
        const unsigned int type = ReadUInt32(stream);
        if ( type != eStdWString )
        {
            throw SerializationException("Expected eStdWString");
        }
        const unsigned int length = ReadUInt32(stream);
        std::vector< wchar_t > tmpBuf( length );
        stream.read( reinterpret_cast< char* > ( tmpBuf.data() ), length );
        return std::wstring( tmpBuf.begin(), tmpBuf.end() );
    }

    static void Write( std::ostream& stream, const unsigned int& item )
    {
        const unsigned int type = eUInt32;
        stream.write( reinterpret_cast< const char* >( &type ), sizeof(type) );
        stream.write( reinterpret_cast< const char* >( &item ), sizeof(item) );
    }

    static unsigned int ReadUInt32( std::istream& stream )
    {
        const unsigned int type = 0;
        stream.read( reinterpret_cast< char* > ( type ), sizeof(type) );
        if ( type != eUInt32 )
        {
            throw SerializationException("Expected eUInt32");
        }
        const unsigned int tmp = 0;
        stream.read( reinterpret_cast< char* > ( tmp ), sizeof(tmp) );
        return tmp;
    }

private:
    enum eTlvBlockTypes
    {
        eStdWString,
        eUInt32
    };
};

int main(int, char**)
{
    std::wstring myStr = L"HelloWorld!";
    int myInt = 0xdeadbeef;

    try
    {
        std::stringstream ss( std::ios_base::out | std::ios_base::in | std::ios_base::binary );
        Serialization::Write( ss, myStr );
        Serialization::Write( ss, myInt );

        myInt = Serialization::ReadUInt32( ss );
        myStr = Serialization::ReadWString( ss );
    }
    catch (const std::runtime_error& ex)
    {
        std::cout << ex.what() << std::endl;
    }
    return 0;
}

然而,在读回流时,我得到一个断言失败,因为流是NULL,有人可以解释为什么这样,以及如何解决它?

编辑:断言失败是ReadUInt32()的第二行。

stream.read( reinterpret_cast< char* > ( type ), sizeof(type) );

你需要解决这个问题:

stream.read( reinterpret_cast< char* > ( type ), sizeof(type) );

对此:

stream.read( reinterpret_cast< char* > ( &type ), sizeof(type) );

它再次显示reinterpret_cast是危险的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM