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)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值