【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可以在网上找到大量源码。
相关文章推荐
- VC轻松解析XML文件--CMarkup使用方法(解决解析中文字符出现乱码问题)
- VC轻松解析XML文件--CMarkup使用方法(解决解析中文字符出现乱码问题)
- 解决windows下使用vc-git提交中文注释乱码的问题
- 关于在MySQL 、 VC、 JSP 中使用UTF-8解决中文生僻字乱码的问题
- 不装oracle客户端使用plsql,以及中文乱码问号问题(也可以解决VC调用oracle 乱码问题)
- PHP使用mb_substr()解决中文字符串截取乱码问题
- 解决springmvc使用@ResponseBody返回String类型字符串中文乱码问题
- PHP使用mb_substr()解决中文字符串截取乱码问题
- 解决asp.net中使用FckEditor上传文件,中文名称乱码的问题
- JSP,mysql,tomcat下(基于struts2)中文及其乱码问题的解决 5大配置点 使用UTF-8编码
- JSP中,AJAX使用POST方式提交中文乱码问题解决
- (2356)Delphi 2010下使用sqlitesimpledelphi连接SQLite数据库及中文乱码问题的解决
- 彻底解决使用Doxygen 1.5.6自动生成的chm文件导航栏中文乱码问题
- 解决QT中文字符串在osg中显示乱码的问题
- 解决HttpClient的FilePart上传文件中使用中文名称文件名乱码问题
- sl3中的DataGrid中的数据导出到Excel中 使用csv格式 解决中文是乱码的问题
- 在win7下使用zend studio 7.1.0,解决汉化、中文乱码、js等问题
- vc编程 UTF-8中文乱码问题解决
- 解决使用nvelocity时候template文件里面包含中文输出结果时候出现乱码的问题
- Ubutun安装netbeans解决中文乱码问题, 使用subversion做版本控制, 使用fcitx输入法