TCustomMemoryStream is an abstract base class used as the common ancestor for memory streams.
Unit
Classes
Description
Use TCustomMemoryStream as a base class when defining a stream object that can transfer data that is stored in memory. Memory streams are useful for providing file-like access to data that is stored in a less accessible medium. Data can be moved to an internal memory buffer when the memory stream is created. After manipulating the data in a memory stream, the data can be written out to its actual storage medium when the memory stream is destroyed.
Do not instantiate an instance of TCustomMemoryStream. It is an abstract class that implements behavior common to all memory streams. To work with an instance of a memory stream, use one of the descendants of TCustomMemoryStream, such as TMemoryStream or TResourceStream.
- { TCustomMemoryStream abstract class }
- TCustomMemoryStream = class(TStream)
- private
- FMemory: Pointer;
- FSize, FPosition: Longint; //大小,当前位置
- protected
- procedure SetPointer(Ptr: Pointer; Size: Longint);
- public
- function Read(var Buffer; Count: Longint): Longint; override;
- function Seek(Offset: Longint; Origin: Word): Longint; override;
- procedure SaveToStream(Stream: TStream);
- procedure SaveToFile(const FileName: string);
- property Memory: Pointer read FMemory;
- end;
- { TCustomMemoryStream }
- procedure TCustomMemoryStream.SetPointer(Ptr: Pointer; Size: Longint);
- begin
- FMemory := Ptr;
- FSize := Size;
- end;
- function TCustomMemoryStream.Read(var Buffer; Count: Longint): Longint;
- begin
- if (FPosition >= 0) and (Count >= 0) then
- begin
- Result := FSize - FPosition;
- if Result > 0 then
- begin
- if Result > Count then Result := Count;
- Move(Pointer(Longint(FMemory) + FPosition)^, Buffer, Result); //复制内存
- Inc(FPosition, Result);
- Exit;
- end;
- end;
- Result := 0;
- end;
- function TCustomMemoryStream.Seek(Offset: Longint; Origin: Word): Longint;
- begin
- case Origin of
- soFromBeginning: FPosition := Offset;
- soFromCurrent: Inc(FPosition, Offset);
- soFromEnd: FPosition := FSize + Offset;
- end;
- Result := FPosition;
- end;
- procedure TCustomMemoryStream.SaveToStream(Stream: TStream);
- begin
- if FSize <> 0 then Stream.WriteBuffer(FMemory^, FSize);
- end;
- procedure TCustomMemoryStream.SaveToFile(const FileName: string);
- var
- Stream: TStream;
- begin
- Stream := TFileStream.Create(FileName, fmCreate);
- try
- SaveToStream(Stream);
- finally
- Stream.Free;
- end;
- end;