生活随笔
收集整理的這篇文章主要介紹了
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 plaincopy
require("alien")?? ?? local?zlib?=?alien.load("zlib1")?? zlib.compressBound:types('long',?'long')?? zlib.compress2:types('int',?'pointer',?'pointer',?'string',?'long',?'int')?? zlib.uncompress:types('int',?'pointer',?'pointer',?'string',?'long')?? ?? local?function?compress(txt)?? ??local?n?=?zlib.compressBound(?? ??local?buf?=?alien.buffer(n)?? ??local?buflen?=?alien.buffer('0000')?? ??local?res?=?zlib.compress2(buf,?buflen,?txt,??? ??assert(res?==?0)?? ??--?返回壓縮結果和壓縮后的長度?? ??return?buf,?alien.toulong(buflen:topointer())?? end?? ?? local?function?uncompress(comp,?comp_len,?n)?? ??local?buf?=?alien.buffer(n)?? ??local?buflen?=?alien.buffer('0000')?? ??local?res?=?zlib.uncompress(buf,?buflen,?comp,?comp_len)?? ??assert(res?==?0)?? ??--?返回解壓后在緩沖區中有效的部分?? ??return?tostr(buf,?alien.toulong(buflen:topointer()))?? ???? end?? ?? --?有符號數轉無符號數?? function?toUnsigned(num)?? ????local?n?? ????if?num?<?0?then?? ????????n?=?256?+?num?? ????else?? ????????n?=?num?? ????end?? ?????? ????return?n?? end?? ?? function?tostr(buf,?len)?? ????local?str?? ????for?i?=?1,?len?do??? ????????--?Lua?把?buf?里面的數當成有符號數了,?? ????????--?導致讀出來的有負數?? ????????local?val?=?toUnsigned(buf[i])?? ????????if?i?==?1?then?? ????????????str?=?string.char(val)?? ????????else?? ????????????str?=?str?..?string.char(val)?? ????????end?? ????end?? ?????? ????return?str?? end?? ?? local?txt?=?string.rep("ab\0cd",?100)?? print("Uncompressed?size:?",??? local?c,?c_len?=?compress(txt)?? print("Compressed?size:?",?c_len)?? local?txt2?=?uncompress(c,?c_len,??? assert(txt2?==?txt)??
總結
以上是生活随笔為你收集整理的Lua 通过 alien 库调用 zlib 压缩/解压的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。