libprotobuf ERROR google/protobuf/wire_format.cc:1059

来源:互联网 发布:如何用阿里云搭建网站 编辑:程序博客网 时间:2024/05/24 03:27

http://blog.csdn.net/jisuanji2121/article/details/9833463

使用google::protobuf进行序列化,在运行时有如下警告!

libprotobuf ERROR google/protobuf/wire_format.cc:1059] Encountered string containing invalid UTF-8 data while serializing protocol buffer. Strings must contain only UTF-8; use the 'bytes' type for raw bytes.

libprotobuf ERROR google/protobuf/wire_format.cc:1059] Encountered string containing invalid UTF-8 data while serializing protocol buffer. Strings must contain only UTF-8; use the 'bytes' type for raw bytes.

原因:要求所有的string类型都必须为UTF-8类型的,可以使用<iconv.h> 进行格式转化。

介绍一下字符集相关知识:


在技术编码方面上,演化顺序为:ASCII ⇒ GB2312 ⇒ GBK ⇒ GB18030


先面贴一段转化的代码:

[cpp] view plaincopy
  1. include <string>  
  2. #include <stdlib.h>  
  3. #include <iostream>  
  4. using namespace std;  
  5. #include <iconv.h>  
  6. bool convertGbk2Utf(string& instr, string& outstr)  
  7. {  
  8.                 iconv_t     gbk2UtfDescriptor;  
  9.                 gbk2UtfDescriptor = iconv_open("UTF-8""GBK");  
  10.                 size_t inlen = instr.length();  
  11.                 char* in = const_cast<char*>(instr.c_str());  
  12.                 size_t outlen = inlen * 2 + 1; // inlen * 1.5 + 1 >= outlen >= inlen + 1  
  13.                 char* outbuf = (char*)::malloc(outlen);  
  14.                 char* out = outbuf;  
  15.                 memset(outbuf, 0x0, outlen);  
  16.                 if((size_t)-1 == iconv(gbk2UtfDescriptor, &in, &inlen, &out, &outlen))  
  17.                 {  
  18.                                 ::free(outbuf);  
  19.                                 return false;  
  20.                 }  
  21.                 outstr.clear();  
  22.                 outstr.append(outbuf);  
  23.                 ::free(outbuf);  
  24.                 return true;  
  25. }  
  26. int main()  
  27. {  
  28.                 string str = "黄";  
  29.                 convertGbk2Utf(str,str);  
  30.                 cout << str << endl;  
  31. }  
0 0