您的位置:首页 > 其它

【thrift】vc中使用thrift中文字符串乱码问题解决

2014-10-25 10:27 906 查看

问题描述:

VC中使用Apache thrift时,如果字符串中包含中文,会出现乱码问题,这个问题的原因是由于thrift为了达到跨语言交互而使用了UTF-8格式发送字符串,这点对java或者C#不会造成影响,但是在VC中UTF-8却很成问题。VC中的string编码随项目编码一般是multibytes或者unicode,虽然倡导使用unicode,但实际上使用multibytes多字节开发仍然广泛存在,下面的解决方案主要解决的是多字节下的乱码问题。

解决方案

1、手动转换

第一种解决方案就是在使用的时候,自己手动转换,读取时从utf-8转为multibytes,写入时从multibytes转为utf-8。显然这样费时费力,只适用于中文字符存在较少的场景。

2、修改thrift lib库

为了达到一劳永逸的目的,可以修改thrift c++ lib库来完成转换,这里只分析使用TBinaryProtocol的场景,其他Protocol如果出现相同情况请参照。

打开TBinaryProtocol.h和TBinaryProtocol.tcc,修改其readString和writeString方法

template <class Transport_>
template<typename StrType>
uint32_t TBinaryProtocolT<Transport_>::readString(StrType& str) {
uint32_t result;
int32_t size;
result = readI32(size);
result += readStringBody(str, size);
//modified by xiaosuiba
//convert utf-8 to multibytes
#ifdef _WIN32
str = utf8_to_mb(str);
#endif
return result;
}


template <class Transport_>
template<typename StrType>
uint32_t TBinaryProtocolT<Transport_>::writeString(const StrType& str) {
//modified by xiaosuiba
//添加多字节到UTF-8转换

#ifdef _WIN32
StrType theStr = mb_to_utf8(str);
#else
const StrType &theStr = str;
#endif

if(theStr.size() > static_cast<size_t>((std::numeric_limits<int32_t>::max)()))
throw TProtocolException(TProtocolException::SIZE_LIMIT);
uint32_t size = static_cast<uint32_t>(theStr.size());
uint32_t result = writeI32((int32_t)size);
if (size > 0) {
this->trans_->write((uint8_t*)theStr.data(), size);
}
return result + size;
}


重新编译lib库,测试OK。

这样会存在一定的效率损失(读取写入都会复制一遍),但是相对于手动转换却能大大节省工作量。

其中的转换函数mb_to_utf8和utf8_to_mb可以在网上找到大量源码。

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐