一:序列化
1.fstream
// Write the new address book back to disk.
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
2.char*
方法二:
int size = address_book.ByteSize();
void *buffer = malloc(size);
address_book.SerializeToArray(buffer, size);
方法三:
使用ostringstream ,
std::ostringstream stream;
address_book.SerializeToOstream(&stream);
string text = stream.str();
char* ctext = string.c_str();
二:反序列化
1.fstream
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
2.char*
address_book.ParseFromArray(char*)
三:repeated 使用
1.添加数据
mLocationInfo = mLocation.add_data();
if(!mLocationInfo)
{
return;
}
mLocationInfo->set_cardid(cardID);
mLocationInfo->set_sleep(speed);
mLocationInfo->set_longitude(longitude);
mLocationInfo->set_latitude(latitude);
mLocationInfo->set_datatime(time);
2.解析数据
message LocationInfo{
uint32 CardID=1;
double Longitude=2;
double Latitude=3;
float Sleep =4;
string Datatime=5;
}
message Location{
string CMD=1;
uint32 CarID=2;
repeated LocationInfo Data=3;
}
Card::Location mLocation;
if (mLocation.ParseFromArray(data, len) == false)//反序列化
{
return "ParseFromArray fail";
}
for (int nLoop = 0; nLoop < mLocation.data_size(); nLoop++)
{
Card::LocationInfo mInfo = mLocation.data(nLoop);//获取对应LocationInfo数据
}