protobuf安装后,在含有protoc执行文件的路径下,执行protoc程序,可以将.proto文件转换为.h和.cc文件。
syntax = "proto2";
package contacts;
//定义联系人message
message PeopleInfo
{
required string name = 1; //姓名
required int32 age = 2; //年龄
required string sex = 3; //姓名
}
执行protoc进程,如下:
protoc --proto_path=/home/ceshi/protobuftest --cpp_out=/home/ceshi/protobuftest /home/ceshi/protobuftest/hello.proto
简要说明:
protoc 转换进程
--path_path .proto文件存放的路径
--cpp_out 生成后的.h和.cc文件存放路径
(1).h 文件
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: hello.proto
#ifndef PROTOBUF_hello_2eproto__INCLUDED
#define PROTOBUF_hello_2eproto__INCLUDED
#include
#include
#if GOOGLE_PROTOBUF_VERSION < 2005000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include
#include
#include
#include
#include
// @@protoc_insertion_point(includes)
namespace contacts {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_hello_2eproto();
void protobuf_AssignDesc_hello_2eproto();
void protobuf_ShutdownFile_hello_2eproto();
class PeopleInfo;
// ===================================================================
class PeopleInfo : public ::google::protobuf::Message {
public:
PeopleInfo();
virtual ~PeopleInfo();
PeopleInfo(const PeopleInfo& from);
inline PeopleInfo& operator=(const PeopleInfo& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _unknown_fields_;
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return &_unknown_fields_;
}
static const ::google::protobuf::Descriptor* descriptor();
static const PeopleInfo& default_instance();
void Swap(PeopleInfo* other);
// implements Message ----------------------------------------------
PeopleInfo* New() const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const PeopleInfo& from);
void MergeFrom(const PeopleInfo& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required string name = 1;
inline bool has_name() const;
inline void clear_name();
static const int kNameFieldNumber = 1;
inline const ::std::string& name() const;
inline void set_name(const ::std::string& value);
inline void set_name(const char* value);
inline void set_name(const char* value, size_t size);
inline ::std::string* mutable_name();
inline ::std::string* release_name();
inline void set_allocated_name(::std::string* name);
// required int32 age = 2;
inline bool has_age() const;
inline void clear_age();
static const int kAgeFieldNumber = 2;
inline ::google::protobuf::int32 age() const;
inline void set_age(::google::protobuf::int32 value);
// required string sex = 3;
inline bool has_sex() const;
inline void clear_sex();
static const int kSexFieldNumber = 3;
inline const ::std::string& sex() const;
inline void set_sex(const ::std::string& value);
inline void set_sex(const char* value);
inline void set_sex(const char* value, size_t size);
inline ::std::string* mutable_sex();
inline ::std::string* release_sex();
inline void set_allocated_sex(::std::string* sex);
// @@protoc_insertion_point(class_scope:contacts.PeopleInfo)
private:
inline void set_has_name();
inline void clear_has_name();
inline void set_has_age();
inline void clear_has_age();
inline void set_has_sex();
inline void clear_has_sex();
::google::protobuf::UnknownFieldSet _unknown_fields_;
::std::string* name_;
::std::string* sex_;
::google::protobuf::int32 age_;
mutable int _cached_size_;
::google::protobuf::uint32 _has_bits_[(3 + 31) / 32];
friend void protobuf_AddDesc_hello_2eproto();
friend void protobuf_AssignDesc_hello_2eproto();
friend void protobuf_ShutdownFile_hello_2eproto();
void InitAsDefaultInstance();
static PeopleInfo* default_instance_;
};
// ===================================================================
// ===================================================================
// PeopleInfo
// required string name = 1;
inline bool PeopleInfo::has_name() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void PeopleInfo::set_has_name() {
_has_bits_[0] |= 0x00000001u;
}
inline void PeopleInfo::clear_has_name() {
_has_bits_[0] &= ~0x00000001u;
}
inline void PeopleInfo::clear_name() {
if (name_ != &::google::protobuf::internal::kEmptyString) {
name_->clear();
}
clear_has_name();
}
inline const ::std::string& PeopleInfo::name() const {
return *name_;
}
inline void PeopleInfo::set_name(const ::std::string& value) {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
name_->assign(value);
}
inline void PeopleInfo::set_name(const char* value) {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
name_->assign(value);
}
inline void PeopleInfo::set_name(const char* value, size_t size) {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
name_->assign(reinterpret_cast(value), size);
}
inline ::std::string* PeopleInfo::mutable_name() {
set_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
name_ = new ::std::string;
}
return name_;
}
inline ::std::string* PeopleInfo::release_name() {
clear_has_name();
if (name_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = name_;
name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
inline void PeopleInfo::set_allocated_name(::std::string* name) {
if (name_ != &::google::protobuf::internal::kEmptyString) {
delete name_;
}
if (name) {
set_has_name();
name_ = name;
} else {
clear_has_name();
name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
}
}
// required int32 age = 2;
inline bool PeopleInfo::has_age() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void PeopleInfo::set_has_age() {
_has_bits_[0] |= 0x00000002u;
}
inline void PeopleInfo::clear_has_age() {
_has_bits_[0] &= ~0x00000002u;
}
inline void PeopleInfo::clear_age() {
age_ = 0;
clear_has_age();
}
inline ::google::protobuf::int32 PeopleInfo::age() const {
return age_;
}
inline void PeopleInfo::set_age(::google::protobuf::int32 value) {
set_has_age();
age_ = value;
}
// required string sex = 3;
inline bool PeopleInfo::has_sex() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void PeopleInfo::set_has_sex() {
_has_bits_[0] |= 0x00000004u;
}
inline void PeopleInfo::clear_has_sex() {
_has_bits_[0] &= ~0x00000004u;
}
inline void PeopleInfo::clear_sex() {
if (sex_ != &::google::protobuf::internal::kEmptyString) {
sex_->clear();
}
clear_has_sex();
}
inline const ::std::string& PeopleInfo::sex() const {
return *sex_;
}
inline void PeopleInfo::set_sex(const ::std::string& value) {
set_has_sex();
if (sex_ == &::google::protobuf::internal::kEmptyString) {
sex_ = new ::std::string;
}
sex_->assign(value);
}
inline void PeopleInfo::set_sex(const char* value) {
set_has_sex();
if (sex_ == &::google::protobuf::internal::kEmptyString) {
sex_ = new ::std::string;
}
sex_->assign(value);
}
inline void PeopleInfo::set_sex(const char* value, size_t size) {
set_has_sex();
if (sex_ == &::google::protobuf::internal::kEmptyString) {
sex_ = new ::std::string;
}
sex_->assign(reinterpret_cast(value), size);
}
inline ::std::string* PeopleInfo::mutable_sex() {
set_has_sex();
if (sex_ == &::google::protobuf::internal::kEmptyString) {
sex_ = new ::std::string;
}
return sex_;
}
inline ::std::string* PeopleInfo::release_sex() {
clear_has_sex();
if (sex_ == &::google::protobuf::internal::kEmptyString) {
return NULL;
} else {
::std::string* temp = sex_;
sex_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
return temp;
}
}
inline void PeopleInfo::set_allocated_sex(::std::string* sex) {
if (sex_ != &::google::protobuf::internal::kEmptyString) {
delete sex_;
}
if (sex) {
set_has_sex();
sex_ = sex;
} else {
clear_has_sex();
sex_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
}
}
// @@protoc_insertion_point(namespace_scope)
} // namespace contacts
#ifndef SWIG
namespace google {
namespace protobuf {
} // namespace google
} // namespace protobuf
#endif // SWIG
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_hello_2eproto__INCLUDED
(2).cc文件
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: hello.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "hello.pb.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
// @@protoc_insertion_point(includes)
namespace contacts {
namespace {
const ::google::protobuf::Descriptor* PeopleInfo_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
PeopleInfo_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_hello_2eproto() {
protobuf_AddDesc_hello_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"hello.proto");
GOOGLE_CHECK(file != NULL);
PeopleInfo_descriptor_ = file->message_type(0);
static const int PeopleInfo_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PeopleInfo, name_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PeopleInfo, age_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PeopleInfo, sex_),
};
PeopleInfo_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
PeopleInfo_descriptor_,
PeopleInfo::default_instance_,
PeopleInfo_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PeopleInfo, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PeopleInfo, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(PeopleInfo));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_hello_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
PeopleInfo_descriptor_, &PeopleInfo::default_instance());
}
} // namespace
void protobuf_ShutdownFile_hello_2eproto() {
delete PeopleInfo::default_instance_;
delete PeopleInfo_reflection_;
}
void protobuf_AddDesc_hello_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\013hello.proto\022\010contacts\"4\n\nPeopleInfo\022\014\n"
"\004name\030\001 \002(\t\022\013\n\003age\030\002 \002(\005\022\013\n\003sex\030\003 \002(\t", 77);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"hello.proto", &protobuf_RegisterTypes);
PeopleInfo::default_instance_ = new PeopleInfo();
PeopleInfo::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_hello_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_hello_2eproto {
StaticDescriptorInitializer_hello_2eproto() {
protobuf_AddDesc_hello_2eproto();
}
} static_descriptor_initializer_hello_2eproto_;
// ===================================================================
#ifndef _MSC_VER
const int PeopleInfo::kNameFieldNumber;
const int PeopleInfo::kAgeFieldNumber;
const int PeopleInfo::kSexFieldNumber;
#endif // !_MSC_VER
PeopleInfo::PeopleInfo()
: ::google::protobuf::Message() {
SharedCtor();
}
void PeopleInfo::InitAsDefaultInstance() {
}
PeopleInfo::PeopleInfo(const PeopleInfo& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
}
void PeopleInfo::SharedCtor() {
_cached_size_ = 0;
name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
age_ = 0;
sex_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
PeopleInfo::~PeopleInfo() {
SharedDtor();
}
void PeopleInfo::SharedDtor() {
if (name_ != &::google::protobuf::internal::kEmptyString) {
delete name_;
}
if (sex_ != &::google::protobuf::internal::kEmptyString) {
delete sex_;
}
if (this != default_instance_) {
}
}
void PeopleInfo::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* PeopleInfo::descriptor() {
protobuf_AssignDescriptorsOnce();
return PeopleInfo_descriptor_;
}
const PeopleInfo& PeopleInfo::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_hello_2eproto();
return *default_instance_;
}
PeopleInfo* PeopleInfo::default_instance_ = NULL;
PeopleInfo* PeopleInfo::New() const {
return new PeopleInfo;
}
void PeopleInfo::Clear() {
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (has_name()) {
if (name_ != &::google::protobuf::internal::kEmptyString) {
name_->clear();
}
}
age_ = 0;
if (has_sex()) {
if (sex_ != &::google::protobuf::internal::kEmptyString) {
sex_->clear();
}
}
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool PeopleInfo::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required string name = 1;
case 1: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_name()));
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::PARSE);
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(16)) goto parse_age;
break;
}
// required int32 age = 2;
case 2: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_age:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &age_)));
set_has_age();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(26)) goto parse_sex;
break;
}
// required string sex = 3;
case 3: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
parse_sex:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_sex()));
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->sex().data(), this->sex().length(),
::google::protobuf::internal::WireFormat::PARSE);
} else {
goto handle_uninterpreted;
}
if (input->ExpectAtEnd()) return true;
break;
}
default: {
handle_uninterpreted:
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
return true;
#undef DO_
}
void PeopleInfo::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// required string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
::google::protobuf::internal::WireFormatLite::WriteString(
1, this->name(), output);
}
// required int32 age = 2;
if (has_age()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->age(), output);
}
// required string sex = 3;
if (has_sex()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->sex().data(), this->sex().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
::google::protobuf::internal::WireFormatLite::WriteString(
3, this->sex(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
}
::google::protobuf::uint8* PeopleInfo::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// required string name = 1;
if (has_name()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->name().data(), this->name().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
1, this->name(), target);
}
// required int32 age = 2;
if (has_age()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->age(), target);
}
// required string sex = 3;
if (has_sex()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->sex().data(), this->sex().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
3, this->sex(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
return target;
}
int PeopleInfo::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required string name = 1;
if (has_name()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->name());
}
// required int32 age = 2;
if (has_age()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->age());
}
// required string sex = 3;
if (has_sex()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->sex());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void PeopleInfo::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const PeopleInfo* source =
::google::protobuf::internal::dynamic_cast_if_available(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void PeopleInfo::MergeFrom(const PeopleInfo& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_name()) {
set_name(from.name());
}
if (from.has_age()) {
set_age(from.age());
}
if (from.has_sex()) {
set_sex(from.sex());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void PeopleInfo::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void PeopleInfo::CopyFrom(const PeopleInfo& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool PeopleInfo::IsInitialized() const {
if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false;
return true;
}
void PeopleInfo::Swap(PeopleInfo* other) {
if (other != this) {
std::swap(name_, other->name_);
std::swap(age_, other->age_);
std::swap(sex_, other->sex_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata PeopleInfo::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = PeopleInfo_descriptor_;
metadata.reflection = PeopleInfo_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace contacts
// @@protoc_insertion_point(global_scope)
#include
#include
#include
#include "hello.pb.h"
using namespace std;
int main(int argc, char* argv[]) {
string people_str;
contacts::PeopleInfo people;
people.set_age(20);
people.set_name("zhangsan");
people.set_sex("nan");
// 调⽤序列化⽅法,将序列化后的⼆进制序列存⼊string中
if (!people.SerializeToString(&people_str))
cout << "序列化联系⼈失败." << endl;
contacts::PeopleInfo peoplere;
// 调⽤反序列化⽅法,读取string中存放的⼆进制序列,并反序列化出对象
if (!peoplere.ParseFromString(people_str))
cout << "反序列化出联系⼈失败." << endl;
cout<< peoplere.name()<< " | " <