hello world 2014. 1. 14. 18:56

Google Protocol Buffer 사용해보기 - 개정판

저번에 너무 대충 쓴거 같아서 차근차근 해볼수 있도록 다시 올려봅니다.


우선 소스를 받습니다. ( https://code.google.com/p/protobuf/ )

까보면 대충 폴더가 이렇습니다.


vsproject 폴더에서 protobuf.sln 파일을 찾아서 visual studio 같은걸로 빌드해줍니다.


debug 나 release 든 폴더에 protoc.exe 파일이 생성됩니다. 이걸로 .proto 파일을 .h 와 .cc 로 만들어 주게 됩니다.

 
message Person {
    required string name = 1;
    required int32  id = 2;
    optional string email = 3;
 
    enum PhoneType {
      MOBILE = 0;
      HOME = 1;
      WORK = 2;
    }

    message PhoneNumber { 
        required string number = 1;
        optional PhoneType type = 2 [ default = HOME ];
    }
    repeated PhoneNumber phone = 4;
}


옵션을 잘 골라서 이전에 만든 proto 파일을 잘 역어주면... pb.cc 파일 과 pb.h 파일이 생성 됩니다.

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto

이라고 tutorial page 에 되어있습니다만 저는 .bat 파일 만들어서 실행하고 있습니다.

del .\output\*.h

del .\output\*.cc

for %%a in (*.proto) do protoc.exe -I=. -I=../../protobuf-2.5.0/src --cpp_out=./output/ %%a

pause

사용할 때는 Directory 와 lib 파일을 설정해야 합니다.

1. Include path : protobug-2.5.0/src


 2. library path : 아까 build한  output 폴더 


 3. library file : libprotobuf.lib



이제 사용할 일만 남았어요


myfile 이라는 파일에 fstream 을 이용해서 저장하고, 다시 파일에서 일거와서 메모리에 가져와서 출력해 보겠습니다.


우선 include 부터 하고

 #include "test.pb.h" 


쓰기.

Person person;                      // proto 에서 저장한 객체를 사용 할 수 있습니다.
person.set_name("John Doe");        // 기본적으로 set_이름, get_이름 을 사용할 수 있습니다.
person.set_id(1234);
person.set_email("123@test.com");

fstream _output( "myfile", ios::out | ios::binary);   
person.SerializeToOstream(&_output);        // myfile 이란 파일에 바로 써버립니다.
_output.close();


읽기.

fstream input( "myfile", ios::in | ios::binary );  // myfile 이란 파일에서 읽습니다.
Person personReadMsg;
PersonReadMsg.ParseFromIstream(&input);
cout << "Name: " << personReadMsg.name() << endl 
       << "Email : " << personReadMsg.email() << endl;


결과 .



간단하게는 이렇게 써볼 수 있습니다.

실제로는 SerializeToString 이라던지 SerializeToArray 함수를 이용해서 소켓 버퍼에 써서 통신하고 있습니다.


한가지 특이한 점?은 동적으로 스키마를 만들 수 있습니다.

DynamicMessageFactory 를 찾아 보시면 됩니다. - 나중에 시간되면 알아보는걸로..


이걸가지고 뭘 하냐면, 클라이언트에서는 proto 파일을 갖고 있지않고, 서버에서 보내준 스키마를 사용합니다.

서버로 부터 받은 스키마를 통해 xml 로 Parsing 해서 가공해서 사용하고 있습니다.


ps : 저번에 쓴글에 오류가 많아서 다시한번 protobuf 에 대해서 써봤습니다. 지난글은 잊어주세요 ㅋㅋㅋ