看了TMemoryStream源代码
如下:
procedure TMemoryStream.SetSize(NewSize: Longint);
var
OldPosition: Longint;
begin
OldPosition := FPosition;
SetCapacity(NewSize);
FSize := NewSize;
if OldPosition > NewSize then Seek(0, soFromEnd);
end;
其中SetCapacity分配新的容量,如下:
procedure TMemoryStream.SetCapacity(NewCapacity: Longint);
begin
SetPointer(Realloc(NewCapacity), FSize);
FCapacity := NewCapacity;
end;
其中SetPointer设置FMemory指针和FSize大小,
关键的Realloc方法如下:
function TMemoryStream.Realloc(var NewCapacity: Longint): Pointer;
begin
if NewCapacity > 0 then
NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
Result := Memory;
if NewCapacity <> FCapacity then
begin
if NewCapacity = 0 then
begin
GlobalFreePtr(Memory);
Result := nil;
end else
begin
if Capacity = 0 then
Result := GlobalAllocPtr(HeapAllocFlags, NewCapacity)
else
Result := GlobalReallocPtr(Memory, NewCapacity, HeapAllocFlags);
if Result = nil then raise EStreamError.Create(SMemoryStreamError);
end;
end;
end;
其中关键代码为:
//原来没有分配内存
if Capacity = 0 then
//新分配
Result := GlobalAllocPtr(HeapAllocFlags, NewCapacity)
else
//重新分配
Result := GlobalReallocPtr(Memory, NewCapacity, HeapAllocFlags);
这两个函数定义如下:
function GlobalAllocPtr(Flags: Integer
Bytes: Longint): Pointer;
{$EXTERNALSYM GlobalAllocPtr}
function GlobalReAllocPtr(P: Pointer
Bytes: Longint
Flags: Integer): Pointer;
{$EXTERNALSYM GlobalReAllocPtr}
是Win32 API,但在Win32 Help中没有找到相关的说明。