提升std :: wstring的C++跨平台(Windows和Mac)序列化

Tym*_*mek 6 c++ serialization boost wofstream

我在一个为Windows(使用Visual Studio 2008)和Mac(使用GCC)构建的程序中使用Boost C++库实现序列化.该程序std::wstring在其大约30个类中使用宽字符串().根据平台的不同,当我保存到文件(通过boost::archive::text_woarchive)时,宽字符串在输出文件中的表示方式不同.

Windows下保存:

H*e*l*l*o* *W*o*r*l*d*!* ...
Run Code Online (Sandbox Code Playgroud)

MacOSX下保存:

H***e***l***l***o*** ***W***o***r***l***d***!*** ...
Run Code Online (Sandbox Code Playgroud)

其中*是NULL字符.

当我尝试使用Mac版本读取在Windows下创建的文件时(反之亦然),我的程序崩溃了.

根据我的理解,到目前为止,Windows本身使用每个宽字符2个字节,而MacOSX(我猜通常使用Unix)使用4个字节.

我所遇到的可能的解决方案,比如utf8_codecvt_facet.cpp,UTF8-CPP,ICUDinkumware的,但我还没有看到一个例子,将与我已经有(例如,我宁愿不重写5个月系列化工作,在工作中这点):

std::wofstream ofs( "myOutputFile" );
boost::archive::text_woarchive oa( ... );
//... what do I put here? ...
oa << myMainClass;
Run Code Online (Sandbox Code Playgroud)

myMainClass 包含宽字符串和Boost智能指针到其他类,反过来,序列化.

vin*_*'th 2

wofstreamtypedef basic_ofstream<wchar_t, char_traits<wchar_t> > wofstream;

在Linux上,您需要声明一个自定义ofstream来处理16位字符(在Linux上)。这可以按如下方式完成:

typedef std::uint16_t Char16_t;
typedef basic_ofstream<Char16_t, char_traits<Char16_t> > wofstream_16;
Run Code Online (Sandbox Code Playgroud)

现在wofstream_16可以在不同平台上无缝使用来处理 16 位宽字符。