: Google " " . , , , .
https://github.com/mwmahlberg/ProtoBufDemo
python, (pip, , ) Go
.proto
.proto . data.proto
syntax = "proto2";
package main;
message Demo {
required uint32 A = 1;
required uint32 B = 2;
// A shortcomning: no 16 bit ints
// We need to make this sure in the applications
required uint32 C = 3;
}
protoc Python Go:
protoc --go_out=. --python_out=. data.proto
data_pb2.py data.pb.go. .
github , ,
go generate
.
Python
import data_pb2
def main():
data = data_pb2.Demo()
data.A = long(5)
data.B = long(5)
data.C = long(2015)
print "* Python writing to file"
f = open('tst.bin', 'wb')
f.write(data.SerializeToString())
f.close()
f = open('tst.bin', 'rb')
read = data_pb2.Demo()
read.ParseFromString(f.read())
f.close()
print "* Python reading from file"
print "\tDemo.A: %d, Demo.B: %d, Demo.C: %d" %(read.A, read.B, read.C)
if __name__ == '__main__':
main()
, protoc, . .
Go
package main
import (
"fmt"
"os"
"github.com/golang/protobuf/proto"
)
func main() {
d := Demo{}
f, _ := os.Open("tst.bin")
fi, _ := f.Stat()
b := make([]byte,fi.Size())
f.Read(b)
proto.Unmarshal(b, &d)
fmt.Println("* Go reading from file")
fmt.Printf("\tDemo.A: %d, Demo.B: %d, Demo.C: %d\n",*d.A,*d.B,*d.C)
}
, , data.proto main.
$ python writer.py && ./ProtoBufDemo
* Python writing to file
* Python reading from file
Demo.A: 5, Demo.B: 5, Demo.C: 2015
* Go reading from file
Demo.A: 5, Demo.B: 5, Demo.C: 2015
, Makefile shorcut , .go :
make run