gpt4 book ai didi

delphi - 读取 blob 字段的问题 - 内存不足

转载 作者:行者123 更新时间:2023-12-04 00:55:06 24 4
gpt4 key购买 nike

我在 Delphi 7 中有一个应用程序,我在其中编写了下面的代码以将大型 PDF 文件从 blob 字段加载到内存,然后加载 PDF,它完美地处理了我已经用 1 GB 文件测试过的大型文件。但是,某处有内存泄漏,我不知道在哪里,在加载 10 个大文件后,它显示消息 - 内存不足。

我不确定加载内存后如何清除内存。

我已经测试加载了几个pdf文件并且它工作完美,组件没有问题。请注意,我不想在组件中加载后将其保存到文件中,我想直接在内存中进行。

请注意,我不想保存到磁盘上的文件然后加载组件,我想直接在内存中执行。

procedure TForm1.btnAbrirClick(Sender: TObject);
var
BlobStream: TStream;
Arquivo: Pointer;
begin
pdf2.Active := False;
Screen.Cursor := crHourGlass;
try
BlobStream := absqry1.CreateBlobStream(absqry1.FieldByName('binario'),bmRead);
Arquivo := AllocMem(BlobStream.Size);
BlobStream.Position := 0;
BlobStream.ReadBuffer(Arquivo^, BlobStream.Size);
pdf2.LoadDocument(Arquivo);
pdfvw1.Active := True;
finally
Screen.Cursor := crDefault;
BlobStream.Free;
Arquivo := nil;
end;
end;

最佳答案

Arquivo := nil; 不会释放 AllocMem 分配的内存。为此,您需要调用 FreeMem

这包含在文档中(强调我的):

AllocMem allocates a memory block and initializes each byte to zero.

AllocMem allocates a block of the given Size on the heap, and returns the address of this memory. Each byte in the allocated buffer is set to zero. To dispose of the buffer, use FreeMem. If there is not enough memory available to allocate the block, an EOutOfMemory exception is raised.

我还更正了您对 try..finally 的使用。

procedure TForm1.btnAbrirClick(Sender: TObject);
var
BlobStream: TStream;
Arquivo: Pointer;
begin
pdf2.Active := False;
Screen.Cursor := crHourGlass;
BlobStream := absqry1.CreateBlobStream(absqry1.FieldByName('binario'),bmRead);
try
Arquivo := AllocMem(BlobStream.Size);
try
BlobStream.Position := 0;
BlobStream.ReadBuffer(Arquivo^, BlobStream.Size);
pdf2.LoadDocument(Arquivo);
pdfvw1.Active := True;
finally
FreeMem(Arquivo);
end;
finally
Screen.Cursor := crDefault;
BlobStream.Free;
end;
end;

关于delphi - 读取 blob 字段的问题 - 内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63107138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com