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

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. -lz
ok 生成lzlib.so
写个测试程序
--test.lua
local tdb= require"lzlib"
local str = "4545453453552525252525252525252525252525252525252525100101101010"
for i =1 ,1 do 
    str =str..str
end

local ss = tdb.lcompress(str)
print("GG",string.len(ss))
local src = tdb.luncompress(ss)
print("FF",src)

“`
这里写图片描述

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值