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;
本文介绍了TCustomMemoryStream类的基本概念及其用法。TCustomMemoryStream作为内存流的基础类,用于提供文件般的访问方式来操作存储在内存中的数据。文章详细解释了其属性和方法,并提供了如何使用该类的实例。
7159

被折叠的 条评论
为什么被折叠?



