tar -xzf protobuf-2.1.0.tar.gz
cd protobuf
./configure --prefix=/usr/local/protobuf
make
make check
make install
3、配置文件
1)vim /etc/profile 和 ~/.profile 中添加:
export PATH=$PATH:/usr/local/protobuf/bin/
export PKG_CONFIG_PATH=/usr/local/protobuf/lib/pkgconfig/
2)配置动态链接库,vim /etc/ld.so.conf,在文件中添加/usr/local/protobuf/lib(注意: 在新行处添加)
3)执行:ldconfig
//在XML中建模Person的name和email字段: <person> <name>John Doe</name> <email>jdoe@example.com</email> </person> //ProtocolBuffer的文本表示: person { name: "John Doe" email: "jdoe@example.com" }
读取数据:
//操作ProtocolBuffer也很简单: cout << "Name: " << person.name() << endl; cout << "E-mail: " << person.email() << endl; //而XML的你需要: cout << "Name: " << person.getElementsByTagName("name")->item(0)->innerText() << endl; cout << "E-mail: " << person.getElementsByTagName("email")->item(0)->innerText() << end;
package tutorial; message Persion { required string name = 1; required int32 age = 2; } message AddressBook { repeated Persion persion = 1; }
#include <iostream> #include <fstream> #include <string> #include "addressbook.pb.h" using namespace std; void PromptForAddress(tutorial::Persion *persion) { cout << "Enter persion name:" << endl; string name; cin >> name; persion->set_name(name); int age; cin >> age; persion->set_age(age); } int main(int argc, char **argv) { //GOOGLE_PROTOBUF_VERIFY_VERSION; if (argc != 2) { cerr << "Usage: " << argv[0] << " ADDRESS_BOOL_FILE" << endl; return -1; } tutorial::AddressBook 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 << "Filed to parse address book." << endl; return -1; } } // Add an address PromptForAddress(address_book.add_persion()); { fstream output(argv[1], ios::out | ios::trunc | ios::binary); if (!address_book.SerializeToOstream(&output)) { cerr << "Failed to write address book." << endl; return -1; } } // Optional: Delete all global objects allocated by libprotobuf. //google::protobuf::ShutdownProtobufLibrary(); return 0; }
#include <iostream> #include <fstream> #include <string> #include "addressbook.pb.h" using namespace std; void ListPeople(const tutorial::AddressBook& address_book) { for (int i = 0; i < address_book.persion_size(); i++) { const tutorial::Persion& persion = address_book.persion(i); cout << persion.name() << " " << persion.age() << endl; } } int main(int argc, char **argv) { //GOOGLE_PROTOBUF_VERIFY_VERSION; if (argc != 2) { cerr << "Usage: " << argv[0] << " ADDRESS_BOOL_FILE" << endl; return -1; } tutorial::AddressBook address_book; { fstream input(argv[1], ios::in | ios::binary); if (!address_book.ParseFromIstream(&input)) { cerr << "Filed to parse address book." << endl; return -1; } input.close(); } ListPeople(address_book); // Optional: Delete all global objects allocated by libprotobuf. //google::protobuf::ShutdownProtobufLibrary(); return 0; }
原文:http://www.cnblogs.com/jeakeven/p/5424301.html