现在的位置: 首页 > 综合 > 正文

VCL类学习之(八) TCustomMemoryStream

2017年12月01日 ⁄ 综合 ⁄ 共 2304字 ⁄ 字号 评论关闭
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.
  1. { TCustomMemoryStream abstract class }
  2.   TCustomMemoryStream = class(TStream)
  3.   private
  4.     FMemory: Pointer;
  5.     FSize, FPosition: Longint;   //大小,当前位置
  6.   protected
  7.     procedure SetPointer(Ptr: Pointer; Size: Longint);
  8.   public
  9.     function Read(var Buffer; Count: Longint): Longint; override;
  10.     function Seek(Offset: Longint; Origin: Word): Longint; override;
  11.     procedure SaveToStream(Stream: TStream);
  12.     procedure SaveToFile(const FileName: string);
  13.     property Memory: Pointer read FMemory;
  14.   end;
  15. { TCustomMemoryStream }
  16. procedure TCustomMemoryStream.SetPointer(Ptr: Pointer; Size: Longint);
  17. begin
  18.   FMemory := Ptr;
  19.   FSize := Size;
  20. end;
  21. function TCustomMemoryStream.Read(var Buffer; Count: Longint): Longint;
  22. begin
  23.   if (FPosition >= 0and (Count >= 0then
  24.   begin
  25.     Result := FSize - FPosition;
  26.     if Result > 0 then
  27.     begin
  28.       if Result > Count then Result := Count;
  29.       Move(Pointer(Longint(FMemory) + FPosition)^, Buffer, Result);    //复制内存
  30.       Inc(FPosition, Result);
  31.       Exit;
  32.     end;
  33.   end;
  34.   Result := 0;
  35. end;
  36. function TCustomMemoryStream.Seek(Offset: Longint; Origin: Word): Longint;
  37. begin
  38.   case Origin of
  39.     soFromBeginning: FPosition := Offset;
  40.     soFromCurrent: Inc(FPosition, Offset);
  41.     soFromEnd: FPosition := FSize + Offset;
  42.   end;
  43.   Result := FPosition;
  44. end;
  45. procedure TCustomMemoryStream.SaveToStream(Stream: TStream);
  46. begin
  47.   if FSize <> 0 then Stream.WriteBuffer(FMemory^, FSize);
  48. end;
  49. procedure TCustomMemoryStream.SaveToFile(const FileName: string);
  50. var
  51.   Stream: TStream;
  52. begin
  53.   Stream := TFileStream.Create(FileName, fmCreate);
  54.   try
  55.     SaveToStream(Stream);
  56.   finally
  57.     Stream.Free;
  58.   end;
  59. end;

抱歉!评论已关闭.