libxml2
似乎将所有的字符串存储在UTF-8中,如xmlChar *
。libxml2 xmlChar * to std :: wstring
/**
* xmlChar:
*
* This is a basic byte in an UTF-8 encoded string.
* It's unsigned allowing to pinpoint case where char * are assigned
* to xmlChar * (possibly making serialization back impossible).
*/
typedef unsigned char xmlChar;
由于libxml2
是一个C库,没有提供程序来得到一个std::wstring
出xmlChar *
的。我想知道的谨慎方式是否xmlChar *
转换为在C++ std::wstring
11是使用mbstowcs C函数,通过这样的事情(工作正在进行中):
std::wstring xmlCharToWideString(const xmlChar *xmlString) {
if(!xmlString){abort();} //provided string was null
int charLength = xmlStrlen(xmlString); //excludes null terminator
wchar_t *wideBuffer = new wchar_t[charLength];
size_t wcharLength = mbstowcs(wideBuffer, (const char *)xmlString, charLength);
if(wcharLength == (size_t)(-1)){abort();} //mbstowcs failed
std::wstring wideString(wideBuffer, wcharLength);
delete[] wideBuffer;
return wideString;
}
编辑:只是一个供参考,我很清楚xmlStrlen
返回什么;这是用于存储字符串的xmlChar
的数量;我知道这不是个字符的数量而是unsigned char
的数量。如果我已经将它命名为byteLength
,那就不那么令人困惑了,但我认为它会更清晰,因为我既有charLength
也有wcharLength
。至于代码的正确性,wideBuffer将会是大于或等于到保存缓冲区所需的大小,总是(我相信)。由于需要比wide_t
更多空间的字符将被截断(我认为)。
如果您想谈论最谨慎的行为方式,请避免使用'wchar_t'和'wstring'。使用Unicode时,它们比弊端更好。 –