LZO 压缩 - 如何设置目标长度?

LZO Compression - How set the destination length?

我正在尝试使用 lzo.dll 来压缩一些文件,我的代码 (Delphi) 是:

function lzo2a_999_compress(const Source: Pointer; SourceLength: LongWord; Dest: Pointer; var DestLength: LongWord; WorkMem: Pointer): Integer; cdecl; external 'lzo.dll';
...
function LZO_compress(FileInput, FileOutput: String): Integer;
var
   FInput, FOutput: TMemoryStream;
   WorkMem: Pointer;
   Buffer: TBytes;
   OutputLength: LongWord;
begin
   FInput := TMemoryStream.Create;
   FOutput := TMemoryStream.Create;
   FInput.LoadFromFile(FileInput);
   FInput.Position := 0;
   GetMem(WorkMem, 1000000);
   OutputLength := ??!?!?!;
   SetLength(Buffer, OutputLength);
   try
      lzo2a_999_compress(FInput.Memory, FInput.Size, Buffer, OutputLength, WorkMem);
   finally
      FOutput.CopyFrom(Buffer, Length(Buffer));
   end;
   FOutput.SaveToFile(FileOutput);
   FreeMem(WorkMem, 1000000);
   FInput.Free;
   FOutput.Free;
end;
...

问题是:如何设置"OutputLength"?我可以分配一个巨大的大小来防止出现问题,但 FOutput 将与缓冲区大小相同。如何只保存 OutputFile 上的压缩数据? 提前致谢。

在函数调用之前你不能(也不需要)知道它。它是一个 var 参数,将由 return 处的函数设置。然后,您可以使用 OutputLength 变量来了解要从缓冲区复制多少字节:

OutputLength := 0; // initialize only
...
try
  lzo2a_999_compress(FInput.Memory, FInput.Size, Buffer, OutputLength, WorkMem);
finally
  FOutput.CopyFrom(Buffer, OutputLength);