Lua 通过 alien 库调用 zlib 压缩/解压

http://blog.csdn.net/kowity/article/details/7256376

上次的文章(http://blog.csdn.net/kowity/article/details/7229815)讲述了上个在 Lua 中调用 zlib 压缩、解压功能的库。其实通过使用 Lua 的 alien 库就可以直接调用外部 dll 中的函数,并不需要专门为 Lua 写一个插件。


调用 zlib 压缩、解压的代码如下(参考了 LuaJIT 的部分实现方式(http://luajit.org/ext_ffi_tutorial.html)):

[python]  view plain copy
  1. require("alien")  
  2.   
  3. local zlib = alien.load("zlib1")  
  4. zlib.compressBound:types('long''long')  
  5. zlib.compress2:types('int''pointer''pointer''string''long''int')  
  6. zlib.uncompress:types('int''pointer''pointer''string''long')  
  7.   
  8. local function compress(txt)  
  9.   local n = zlib.compressBound(#txt)  
  10.   local buf = alien.buffer(n)  
  11.   local buflen = alien.buffer('0000')  
  12.   local res = zlib.compress2(buf, buflen, txt, #txt, 9)  
  13.   assert(res == 0)  
  14.   -- 返回压缩结果和压缩后的长度  
  15.   return buf, alien.toulong(buflen:topointer())  
  16. end  
  17.   
  18. local function uncompress(comp, comp_len, n)  
  19.   local buf = alien.buffer(n)  
  20.   local buflen = alien.buffer('0000')  
  21.   local res = zlib.uncompress(buf, buflen, comp, comp_len)  
  22.   assert(res == 0)  
  23.   -- 返回解压后在缓冲区中有效的部分  
  24.   return tostr(buf, alien.toulong(buflen:topointer()))  
  25.     
  26. end  
  27.   
  28. -- 有符号数转无符号数  
  29. function toUnsigned(num)  
  30.     local n  
  31.     if num < 0 then  
  32.         n = 256 + num  
  33.     else  
  34.         n = num  
  35.     end  
  36.       
  37.     return n  
  38. end  
  39.   
  40. function tostr(buf, len)  
  41.     local str  
  42.     for i = 1, len do   
  43.         -- Lua 把 buf 里面的数当成有符号数了,  
  44.         -- 导致读出来的有负数  
  45.         local val = toUnsigned(buf[i])  
  46.         if i == 1 then  
  47.             str = string.char(val)  
  48.         else  
  49.             str = str .. string.char(val)  
  50.         end  
  51.     end  
  52.       
  53.     return str  
  54. end  
  55.   
  56. local txt = string.rep("ab\0cd"100)  
  57. print("Uncompressed size: "#txt)  
  58. local c, c_len = compress(txt)  
  59. print("Compressed size: ", c_len)  
  60. local txt2 = uncompress(c, c_len, #txt)  
  61. assert(txt2 == txt)  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值