libprotobuf ERROR google/protobuf/wire_format.cc:1059

本文详细介绍了在使用google::protobuf进行序列化时遇到的关于字符串编码的警告问题,并提供了解决方案。通过使用<iconv.h>进行格式转化,可以将非UTF-8格式的字符串转换为UTF-8格式,从而避免警告提示。同时,文章还简要介绍了字符集的相关知识,以及在编码方面从ASCII到GB18030的演化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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

 

先面贴一段转化的代码:

 

 

include <string>
#include <stdlib.h>
#include <iostream>
using namespace std;
#include <iconv.h>
bool convertGbk2Utf(string& instr, string& outstr)
{
                iconv_t     gbk2UtfDescriptor;
                gbk2UtfDescriptor = iconv_open("UTF-8", "GBK");
                size_t inlen = instr.length();
                char* in = const_cast<char*>(instr.c_str());
                size_t outlen = inlen * 2 + 1; // inlen * 1.5 + 1 >= outlen >= inlen + 1
                char* outbuf = (char*)::malloc(outlen);
                char* out = outbuf;
                memset(outbuf, 0x0, outlen);
                if((size_t)-1 == iconv(gbk2UtfDescriptor, &in, &inlen, &out, &outlen))
                {
                                ::free(outbuf);
                                return false;
                }
                outstr.clear();
                outstr.append(outbuf);
                ::free(outbuf);
                return true;
}
int main()
{
                string str = "黄";
                convertGbk2Utf(str,str);
                cout << str << endl;
}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值