I'm trying use lzo.dll to compress some file, my code(Delphi) is that:
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;
...
The problem is: how set the "OutputLength"? I can allocate a huge size to prevent problems but the FOutput will be the same size of the Buffer. How can I save only the compressed data on OutputFile? Thanks in advance.
You can not (and need not) know it before the function call. It is a var
parameter and will be set by the function at return. You can then use your OutputLength
variable to know how many bytes to copy from the buffer:
OutputLength := 0; // initialize only
...
try
lzo2a_999_compress(FInput.Memory, FInput.Size, Buffer, OutputLength, WorkMem);
finally
FOutput.CopyFrom(Buffer, OutputLength);