protobuf(fpc)
//cxg 2021-8-11 protobuf unit Unit1; {$mode objfpc}{$H+} interface uses protobuf_fpc, protobuf_fpc_types, Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TPeople } //message People { // required Int32 Code = 1; // required string FirstName = 2; // optional string LastName = 3; //} TPeople = class(TSerializationObject) //message People private FCode: Int32; FFirstName: string; FLastName: string; protected procedure InternalRegisterProperty; override; procedure InternalInit; override; public published property Code:Int32 read FCode write FCode; //1; property FirstName:string read FFirstName write FFirstName;//2; property LastName:string read FLastName write FLastName;//3; end; TPeoples = specialize GSerializationObjectList<TPeople>; { TPeopleArr } TPeopleArr = class(TSerializationObject) private FPeopleArr: TPeoples; protected procedure InternalRegisterProperty; override; procedure InternalInit; override; published property PeopleArr: TPeoples read FPeopleArr write FPeopleArr; end; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TPeopleArr } procedure TPeopleArr.InternalRegisterProperty; begin inherited InternalRegisterProperty; RegisterProp('PeopleArr', 1); end; procedure TPeopleArr.InternalInit; begin inherited InternalInit; FPeopleArr := TPeoples.create; end; { TForm1 } procedure TForm1.Button1Click(Sender: TObject); var P, p2: TPeople; b: tbytesstream; begin p:=TPeople.Create; p.Code:=1; p.FirstName:='第一名称'; p.LastName:='第二名称'; b := tbytesstream.Create; p.SaveToStream(b); p.free; p2 := TPeople.Create; p2.LoadFromStream(b); b.free; memo1.Lines.Add(p2.Code.tostring); memo1.Lines.Add(p2.FirstName); memo1.Lines.Add(p2.LastName); p2.free; end; procedure TForm1.Button2Click(Sender: TObject); var arr, arr2: tpeoplearr; p, p2: TPeople; b: tbytesstream; begin arr := tpeoplearr.Create; p := arr.PeopleArr.AddItem; p.Code:=1; p.FirstName:='第一名称'; p.LastName:='第二名称'; p := arr.PeopleArr.AddItem; p.Code:=2; p.FirstName:='fname2'; p.LastName:='lname2'; b := tbytesstream.Create; arr.SaveToStream(b); arr.Free; arr2 := tpeoplearr.Create; arr2.LoadFromStream(b); b.free; for p2 in arr2.PeopleArr do begin memo1.Lines.Add(p2.Code.tostring); memo1.Lines.Add(p2.FirstName); memo1.Lines.Add(p2.LastName); end; arr2.free; end; { TPeople } procedure TPeople.InternalRegisterProperty; begin inherited InternalRegisterProperty; RegisterProp('Code', 1); RegisterProp('FirstName', 2); RegisterProp('LastName', 3); end; procedure TPeople.InternalInit; begin inherited InternalInit; end; end.