procedure writestring(MS:TMemoryStream;const Str:string );
var
Len: Integer;
begin
Len := Length(Str);
MS.Write(Len, SizeOf(Integer));
if Len > 0 then MS.Write(PChar(Str)^, Len);
end;
function readstring(MS:TMemoryStream):string;
var
Len: Integer;
begin
Result := '';
MS.Read(Len, SizeOf(Integer));
if Len > 0 then
begin
SetLength(Result, Len);
MS.Read(Pointer(Result)^, Len);
end;
end;
-------------
var
MS:TMemoryStream;
begin
MS:=TMemoryStream.Create(self);
writestring(MS,'Write a String1!');
writestring(MS,'Write a String2!');
MS.Position :=0;
showmessage(readstring(MS));// Write a String1!
showmessage(readstring(MS));// Write a String2!
MS.Free;
end;
大致这样,没有很好的测试!
你可以参照writestring和readstring,从TMemoryStream继承建一个类,把这两个过程
作为扩展的方法添加进去,算了,给你写完整吧!好用,测试过的!
unit WSStream;
interface
uses
classes;
type
TWSStream = class(TMemoryStream)
public
procedure WriteString(Const Value:String);
function ReadString:String;
end;
implementation
{ TWSStream }
function TWSStream.ReadString: String;
var
Len: Integer;
begin
Result := '';
Read(Len, SizeOf(Integer));
if Len > 0 then
begin
SetLength(Result, Len);
Read(Pointer(Result)^, Len);
end;
end;
procedure TWSStream.WriteString(const Value: String);
var
Len: Integer;
begin
Len := Length(Value);
Write(Len, SizeOf(Integer));
if Len > 0 then Write(PChar(Value)^, Len);
end;
end.