VC中使用Apache thrift時,如果字符串中包含中文,會出現亂碼問題,這個問題的原因是由於thrift為了達到跨語言交互而使用了UTF-8格式發送字符串,這點對java或者C#不會造成影響,但是在VC中UTF-8卻很成問題。VC中的string編碼隨項目編碼一般是multibytes或者unicode,雖然倡導使用unicode,但實際上使用multibytes多字節開發仍然廣泛存在,下面的解決方案主要解決的是多字節下的亂碼問題。
第一種解決方案就是在使用的時候,自己手動轉換,讀取時從utf-8轉為multibytes,寫入時從multibytes轉為utf-8。顯然這樣費時費力,只適用於中文字符存在較少的場景。
為了達到一勞永逸的目的,可以修改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可以在網上找到大量源碼。