FFI和第三方模块

一、FFI

FFI是 LuaJIT 中的一个扩展库,它允许我们使用 Lua 代码调用C语言的数据结构和函数。

FFI库在很大程度上避免了在C中编写繁琐的手动 Lua/C 绑定的需要。无需学习单独的绑定语言 - 它解析普通的C声明!这些可以从C头文件或参考手册中剪切粘贴。

如何调用外部C库函数呢?
1、加载FFI库。
2、为函数添加C声明。
3、调用命名的C函数。

看一个官方提供的简单示例:

-- test_ffi.lua

local ffi = require("ffi")
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("Hello %s!", "world")

运行:

luajit test_ffi.lua

详见:http://luajit.org/ext_ffi.html

https://moonbingbing.gitbooks.io/openresty-best-practices/content/lua/FFI.html

二、增加第三方模块

默认的 resty 库所在位置:

使用第三方库原则:

star数量比较多,更新比较频繁,contributer人比较多

安装第三方http库:

git clone https://github.com/ledgetech/lua-resty-http

copy三方库lib/resty/*到/opt/openresty/lulib/resty

cp lua-resty-http/lib/resty/* /opt/openresty/lualib/resty

使用示例:

local http = require "resty.http"
local httpc = http.new()

local res, err = httpc:request_uri("http://example.com/helloworld", {
    method = "POST",
    body = "a=1&b=2",
    headers = {
      ["Content-Type"] = "application/x-www-form-urlencoded",
    },
    keepalive_timeout = 60,
    keepalive_pool = 10
})

if not res then
    ngx.say("failed to request: ", err)
    return
end

ngx.status = res.status

for k,v in pairs(res.headers) do
  --
end

ngx.say(res.body)
发布了524 篇原创文章 · 获赞 172 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/INGNIGHT/article/details/104868167