在TMemoryStream中使用动态记录

时间:2011-11-30 12:01:45

标签: delphi persistence

我使用TMemoryStream使用indy TCPServer发送动态记录。

我的记录结构如下:

TMyRecord = record
  name : string ;  // unassigned size
  ID : integer ;
  Picture : TJPEGImage ;  
end;

如何将此记录类型的变量分配到TMemoryStream中? 另请解释如何将此TMemoryStream提取为记录类型。

1 个答案:

答案 0 :(得分:3)

基本理念是

Tmyrecord = Record
  name : string ;  // unassaigned 
  ID : integer ;
  Picture : TJPEGImage ;
  procedure SaveToStream(const aStream: TStream);
  procedure LoadFromStream(const aStream: TStream);
end;

procedure Tmyrecord.SaveToStream(const aStream: TStream);
var Len: Integer;
begin
  // save the length of name str
  Len := Length(name);
  aStream.Write(Len, SizeOf(Len));
  // save the name
  if(Len > 0)then aStream.Write(name[1], Len * SizeOf(name[1]));
  // save the ID
  aStream.Write(ID, SizeOf(ID));
  // save image
  Picture.SaveToStream(aStream);
end;

procedure Tmyrecord.LoadFromStream(const aStream: TStream);
var Len: Integer;
begin
  // read the length of name str
  aStream.Read(Len, SizeOf(Len));
  if(Len > 0)then begin
     // read the name
     SetLength(name, Len);
     aStream.Read(name[1], Len * SizeOf(name[1]));
  end else name := '';
  // load the ID
  aStream.Read(ID, SizeOf(ID));
  // load image
  if(Picture = nil)then Picture := TJPEGImage.Create;
  Picture.LoadFromStream(aStream);
end;