Delphi中流对象的应用

时间:2022-01-12 20:47:28

Delphi的流对象(TStream的派生对象)有如下读写函数:

function Read(var Buffer; Count: Longint): Longint;
function Write(const Buffer; Count: Longint): Longint;
procedure ReadBuffer(var Buffer; Count: Longint);
procedure WriteBuffer(const Buffer; Count: Longint);

Buffer是Var或const类型,它们都是无类型参数,所以对其处理都使用指针.

通常我们会用流来处理长的字符串,但是用字符串类型作为Buffer参数会导致错误的结果.

因为字符串包括大小,引用计数,字符存储地址等信息.为了在流中正确处理字符串,要将其转为Pointer对或PChar.

示例如下:

var
 s1,s2:string;
 MemStream:TMemoryStream;
begin
  MemStream:=TMemoryStream.Create;
  s1:='this is a string test!';
  MemStream.SetSize(length(s1));
  MemStream.Write(PChar(s1)^,length(s1));
  SetLength(s2,length(s1));
  MemStream.Position:=0;
  MemStream.Read(PChar(s2)^,length(s1));
  ShowMessage(s2);
  MemStream.Clear;
  MemStream.Free;
end;

http://www.cnblogs.com/dashan9zj/archive/2009/01/14/1375261.html