Visual Studio .NET 2002Visual C++ 7.0.NET 1.0C++/CLIWindows 2003Windows 2000Windows XP中级开发Visual StudioWindowsC++.NET
.NET libbz2 封装






4.44/5 (9投票s)
2003年7月15日
1分钟阅读

133720

1383
.NET libbz2 封装,使用 MC++ 编写
BzipStream
BzipStream 是一个用于 Bzip2 压缩工具的小型 .NET 封装。Bz2 压缩类似于 Gzip,它只压缩单个文件/块/blob,不同于 zip、rar、ace 等。它通常用于压缩 tarball (.tar 文件)。
以下是实现图
public class BzipStream : Stream
{
public BzipStream(string filename, FileAccess mode);
public override void Close();
public static byte[] Compress(byte[] buffer);
public static byte[] Compress(byte[] buffer, int level);
public static byte[] Decompress(byte[] buffer);
public override void Flush();
public static BzipStream OpenRead(string filename);
public static BzipStream OpenWrite(string filename);
public override int Read(byte[] buffer, int start, int length);
public override long Seek(long pos, SeekOrigin origin);
public override void SetLength(long len);
public override void Write(byte[] buffer, int start, int length);
public override bool CanRead { get; }
public override bool CanSeek { get; }
public override bool CanWrite { get; }
public override long Length { get; }
public override long Position { get; set; }
}
De/Compress 方法是快速解压缩 byte[] 的实用方法。以下方法已实现但不受支持
长度
职位
Seek
此外,FileAccess.ReadWrite
不受支持。
用法 (C#)
BzipStream bz = new BzipStream("file.bz2", FileAccess.Write);
Stream s = File.OpenRead("file");
int len = 8192;
byte[] buffer = new byte[len];
while ((len = s.Read(buffer, 0, len)) > 0)
{
bz.Write(buffer, 0, len);
}
s.Close();
bz.Close();
//or using utility methods
byte[] cbuff = BzipStream.Compress(buffer);
buffer = BzipStream.Decompress(cbuff);
实现
libbz2 编译为纯 C,单个文件 (dotbz2.cpp) 包含 MC++ 实现(并且只有该文件设置了“托管”编译标志)。很多人都在问如何做到这一点。很简单。看看就行了。
基本模式是
- 获取 .NET 对象
- 在堆上分配内存
- 复制对象并获取
IntPtr
- 将
IntPtr
转换为void*
- 转换为
<T>*
- 执行非托管函数
- 将结果转换为
void*
- 转换为
IntPtr
- 从堆复制到对象
- 释放堆内存
步骤 7 和 8 实际上不是必需的,因为我们已经有了对 IntPtr
的引用。
结论
这只是一个如何用 MC++ 封装 C 库的小例子。欢迎提出建议。我可以粘贴代码,只有 185 行。不要因为文章的长度而责怪我。:)