如何为 LZMA (7zip) SDK encoder.Code() 函数创建回调函数?

How do I create a callback function for the LZMA (7zip) SDK encoder.Code() function?

下面是 class 我正在为找到的 here LZMA (7zip) SDK 构建的一小段摘录。大多数情况下一切似乎都正常,但我正在尝试实施一些进度报告来跟踪压缩过程的进度。在 encoder.Code(inStream, outStream, -1, -1, null); 下面的行中,当我需要使用某种形式的 ICodeProgress 回调时,我使用 null

我只想创建某种类型的委托回调来跟踪我在 class 中创建的线程内的进度。

Class 摘录:

public class CompressorThreads : CompressorClassEvents
{
    public static class SevenZipCoderProperties
    {
        public static readonly CoderPropID[] PropertyNames =
        {
            CoderPropID.DictionarySize,
            CoderPropID.PosStateBits,
            CoderPropID.LitContextBits,
            CoderPropID.LitPosBits,
            CoderPropID.Algorithm,
            CoderPropID.NumFastBytes,
            CoderPropID.MatchFinder,
            CoderPropID.EndMarker,
        };

        public static readonly object[] PropertyValues =
        {
            (Int32)LzmaDictionarySize.VerySmall,
            (Int32)(2),
            (Int32)(3),
            (Int32)(0),
            (Int32)(2),
            (Int32)LzmaSpeed.Fastest,
            "bt4",
            true,
        };
    }


    private void Compress(string filePath, string compressedFilePath)
    {
        //Get the bytes of the file
        byte[] fileInBytes = File.ReadAllBytes(filePath);

        //Setup the encoder
        SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder();
        encoder.SetCoderProperties(SevenZipCoderProperties.PropertyNames, SevenZipCoderProperties.PropertyValues);

        using (MemoryStream outStream = new MemoryStream())
        {
            encoder.WriteCoderProperties(outStream);

            //Get the file bytes into a memory then compress them
            using (MemoryStream inStream = new MemoryStream(fileInBytes))
            {
                long uncompressedFilesize = inStream.Length;

                for (int i = 0; i < 8; i++)
                        outStream.WriteByte((Byte)(uncompressedFilesize >> (8 * i)));

                encoder.Code(inStream, outStream, -1, -1, null);
            }

            //Write the compressed file
            compressedFileSize = outStream.Length;
            using (FileStream file = new FileStream(compressedFilePath, FileMode.Create, FileAccess.Write))
            {
                outStream.WriteTo(file);
            }
        }
    }
}

ICodeProgress 是一个接口,因此您需要在某处实现它。您可以在 class 中实现 ICodeProgress 接口并传递 this 而不是 null.

例如,您可以这样做:

class CompressorThreads : CompressorClassEvents, ICodeProgress
{
    void ICodeProgress.SetProgress(long inSize, long outSize)
    {
        System.Diagnostics.Debug.WriteLine("processedInSize:" + inSize + "  processedOutSize:" + outSize);
    }
    private void Compress(string filePath, string compressedFilePath)
    {
        . . .
        encoder.Code(inStream, outStream, -1, -1, this);
        . . .
    }
}