我使用TMemoryStream
使用indy TCPServer
发送动态记录。
我的记录结构如下:
TMyRecord = record
name : string ; // unassigned size
ID : integer ;
Picture : TJPEGImage ;
end;
如何将此记录类型的变量分配到TMemoryStream中? 另请解释如何将此TMemoryStream提取为记录类型。
答案 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;