我似乎无法让zlib对windows下的mingw做任何事情。
我下载了zlib @ http://sourceforge.net/projects/mingw/files_beta/MinGW/zlib/zlib-1.2.3-1-mingw32/并将头文件和lib文件放在正确的位置。
简单的代码如:
#include <stdlib.h>
#include <stdio.h>
#include "zlib.h"
int main(int argc, char *argv[])
{
long a;
char buffer[1024];
a = 1024;
compress(buffer,&a,"testing",7);
return 0;
}
编译:
gcc test.c -lzlib -Wall -o test.exe
编译好。然而,exe在压缩功能崩溃。有任何想法吗?
我推荐使用MSYS2来做这种事情。这些指令假设您要编译64位程序,但可以轻松地将它们修改为32位。
安装MSYS2后,在“开始”菜单中运行“MinGW-w64 Win64 Shell”快捷方式。运行以下命令安装64位工具链:
pacman -S mingw-w64-x86_64-toolchain mingw-w64-x86_64-zlib
然后通过运行以下代码来编译代码:
gcc test.c -lz -o test
我没有仔细检查你的代码,但我能够运行你的代码而不会崩溃,所以你的代码可能没问题。您的代码也没有输出,因此很难判断它是否真的有效。
看看zlib手册,它说:
ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen));
将源缓冲区压缩到目标缓冲区。 sourceLen是源缓冲区的字节长度。在进入时,destLen是目标缓冲区的总大小,它必须至少是compressBound(sourceLen)返回的值。退出时,destLen是压缩缓冲区的实际大小。
也许a=1024
不够大?我想你需要调用compressBound
来获得合适的价值。
我尝试使用MSYS中的zlib(可以使用mingw-get访问)并遇到如下所述的相同问题。
解决方案是执行静态链接而不是使用共享库。只需删除或重命名导入库libz.dll.a,以避免链接器与msys-z.dll建立链接。
重新编译,它将工作。
另一种方法是自己从zlib.net网站安装zlib。从mingw-get中删除一个。
在代码中使用zlib非常简单,文档(或我发现的stackoverflow上的各种答案)并不明显。
以下技术适用于任何编译器和IDE。我在windows mingw中使用代码:blocks测试它,这就是为什么我发布它作为这个问题的答案。
而已。这简直太难了。
所有你必须要小心的是内存管理,因为这是c代码。
为了让自己更简单,我已经整理了一个c ++包装器,欢迎您使用,如下所示:
/** ZLIB C++ wrapper
Usage:
<pre>
#include "cZLIB.h"
{
// compress data in bigbuffer
raven::set::cZLIB ZLIB;
ZLIB.Compress( bigbuffer, sizebigbuffer );
// use compressed buffer, before ZLIB goes out of scope
use( ZLIB.Buffer(), ZLIB.Length() );
}
...
{
// decompress data in smallbuffer
raven::set::cZLIB ZLIB;
ZLIB.Inflate( smallbuffer, sizesmallbuffer )
// use decompressed data, before ZLIB goes out of scope
use( ZLIB.Buffer(), ZLIB.Length() );
}
</pre>
Build:
Download this code ( cZLIB.h and cZLIB.cpp ) from
https://github.com/JamesBremner/raven-set
and install somewhere in your compiler search path.
Let's assume you install it in folder .../src.
Download the zlib source code from http://www.zlib.net/
Copy all the .c and .h files from the root folder of the zlib source
to a new folder .../src/zlib
Add the files cZLIB.h, cZLIB.cpp and all the files in .../src/zlib
to the IDE project.
Build.
*/
class cZLIB
...