zilb导出解压缩接口给lua调用

来源:互联网 发布:jira 数据库配置 编辑:程序博客网 时间:2024/06/05 04:40

1.编译zlib
下载zlib http://www.zlib.net/
解压执行
./configure
make
make install(这个可有可无)
生成了libz.so.1.2.11
2.写导出方法

//lzlib.c#include <unistd.h>#include <stdlib.h>#include <string.h>#include <arpa/inet.h> #include "stdio.h"#include "zlib.h"#include "lua.h"#include "lualib.h"#include "lauxlib.h"//正常压缩static int ccompress(lua_State *L){    char* buf = NULL;    size_t slen = 0;    const char *str = lua_tolstring(L, 1,&slen);    printf("ccompress slen %d \n",(unsigned int)slen);    uLong dlen = compressBound(slen);    if((buf = (char*)malloc(sizeof(char) * (dlen))) == NULL)    {         printf("no enough memory!\n");         return 0;    }    if(compress((Bytef*)(buf), &dlen, (const Bytef*)str, slen) != Z_OK)    {        printf("compress failed!\n");        free(buf);        return 0;    }    else    {        lua_pushlstring(L, (char*)buf,dlen);        printf("ccompress succ %d\n",(unsigned int)dlen);        free(buf);        return 1;    }}//解压缩static int cuncompress(lua_State *L){    size_t slen = 0;        const char *strBuf = lua_tolstring(L, 1,&slen);    printf("cuncompress slen %d\n",(unsigned int)slen);    uLong dLen;    dLen = slen * 500; //压缩前数据长度未知,默认为压缩后长度的500倍    char* buf = NULL;    if((buf = (char*)malloc(sizeof(char) * dLen)) == NULL)    {        printf("no enough memory!\n");        return 0;    }    int res = uncompress((Bytef*)buf, &dLen, (const Bytef*)strBuf, slen);    printf("unzip res %d\n",res);    if (res != Z_OK)    {        printf("uncompress failed!\n");        free(buf);        return 0;    }    else    {        printf("uncompress succ! \n");        lua_pushlstring(L, (char*)buf,dLen);        free(buf);        return 1;    }}int luaopen_lzlib(lua_State *L){    luaL_checkversion(L);    luaL_openlibs(L);    luaL_Reg l[] = {        { "lcompress",ccompress},        { "luncompress",cuncompress},        { NULL, NULL },    };    luaL_newlib(L,l);    return 1;}简单粗暴的方法,把zlib.h,zconf.h,zlib库,lzlib.c放到一个目录编译: gcc -o lzlib.so lzlib.c -shared -fpic -L. -lzok 生成lzlib.so写个测试程序--test.lua
local tdb= require"lzlib"local str = "4545453453552525252525252525252525252525252525252525100101101010"for i =1 ,1 do     str =str..strendlocal ss = tdb.lcompress(str)print("GG",string.len(ss))local src = tdb.luncompress(ss)print("FF",src)

“`
这里写图片描述

解压缩优化:
压缩的时候可以把源文件的长度和压缩后的长度写到压缩后的数据前面,作为头信息8个字节长度,解压的时候先解头数据就可以准确知道源文数长度,从而不用开辟500倍的空间。

原创粉丝点击