luajit ffi 小结
luajit ffi 小结
Lua 是一种语法简单,上手快的语言,虽然原生库比较少,但是可以方便的和 C 语言互相调用,常被用于脚本嵌入到 C 程序中。如 Redis 中可以加载 Lua 脚本,作用类似于存储过程,Nginx 中 lua-nginx-module 模块更是将 Lua 的这种特性发挥到极致。
使用 Lua 如何调用 C 的函数,个人认为是每一个 Lua 开发者必学的内容。Lua 调用 C 程序有两种方法,一种是使用 lua C API,另一种方法就是使用 luajit 提供的 ffi 库来调用 C 程序。本文主要是对 luajit ffi 的研究总结。
luajit ffi
luajit 和 lua 一样,是可以直接安装在操作系统中的,相关介绍直接参考官网 luajit。个人测试效果来看,luajit 的执行效率远高于 lua,大概是 8 倍左右。openresty 的 lua-nginx-module 模块就是将 luajit 集成到了 Nginx 中,实现在 Nginx 中执行 Lua 脚本
luajit ffi 是 luajit 提供给 Luaer 使用 Lua 调用 C 函数的 Lua 库,使用该库,Luaer 不用再去操作复杂的 Lua 栈来粘合两种程序代码,luajit ffi 官方资料。
引入 luajit ffi 库
local ffi = require("ffi")
在 Lua 中调用 C 函数
和 lua 的 C API 一样,Lua 调用 C 函数,需要将 C 函数编译成链接库。区别在于 C API 查找 C 的 Lua 库是在 package.cpath 路径下进行查找,而这些库函数使用 Lua 栈接口进行编写。而 luajit 对于 C 链接库的引用遵从于普通 C 库的引用方式,先在 /usr/lib(/usr/lib64),/lib(/lib64) 目录下查找,再到用户自定义的 LD_LIBRARY_PATH 下查找。
本节涉及接口:
- ffi.cdef[[c_function define]]
- ffi.C
- ffi.load(name [,global])
调用 C 标准库函数
对于 C 标准库函数引用,需要引入函数,函数声明
ffi.cdef[[c_function define]]
调用 C 函数
ffi.C.c_function
如:
local ffi = require("ffi")ffi.cdef[[ int printf(const char *fmt, ...); int strcasecmp(const char *s1, const char *s2); ]]ffi.C.printf("Hello %s!\n", "world") ret = ffi.C.strcasecmp("Hello", "hello") print(ret) ret = ffi.C.strcasecmp("Hello", "hello1") print(ret)
输出结果
[root@AlexWoo-CentOS lua]# luajit ffic.lua Hello world! 0 -49
调用自定义的 C 函数
调用自定义的 C 函数,首先要将自定义的 C 函数编译成链接库
[root@AlexWoo-CentOS lua]# cat ffimyc.c int add(int x, int y) {return x + y; } [root@AlexWoo-CentOS lua]# gcc -g -o libffimyc.so -fpic -shared ffimyc.c
比调用 C 标准库函数,需要在 Lua 中引入相应的库
ffi.load(name [,global])
这里第二个参数如果为 true,则该库被引入全局命名空间,这里使用 ffi.load 需要注意两点:
链接库文件必须在 C 的动态链接库查找路径中,否则会报类似错误:
luajit: ffimyc.lua:3: libffimyc.so: cannot open shared object file: No such file or directory
引入方法:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:your_lib_path
在 Linux 下,库函数名的查找与 C 程序查找动态链接库相同,如上面我生成的动态链接库文件为 libffimyc.so,我在 ffi.load 中的 name 为 ffimyc
调用自己的函数,可以直接使用 ffi.load 返回的变量调用,下面我们看一个简单的例子:
local ffi = require('ffi')myc = ffi.load('ffimyc')ffi.cdef[[ int add(int x, int y); ]]ret = myc.add(1, 20) print(ret)
输出结果
[root@AlexWoo-CentOS lua]# luajit ffimyc.lua 21
使用 ffi.C 调用自定义的 C 函数
上面的例子中,是不能直接使用 ffi.C 来调用 add 函数的,那么怎么用 ffi.C 来调用 add 函数,对,就是 ffi.load 时,第二个参数置为 true,将库加载为全局命名空间。示例:
local ffi = require('ffi')ffi.load('ffimyc', true)ffi.cdef[[ int add(int x, int y); ]]ret = ffi.C.add(1, 10) print(ret)
输出结果
[root@AlexWoo-CentOS lua]# luajit ffimyc.lua 11
本节小结
- 在 lua 中调用 C 函数,需要使用 ffi.cdef 对 C 函数进行声明
- 对于 C 标准库函数,已在全局命名空间,直接可以使用 ffi.C.函数名(函数参数…) 来调用函数
- 对于自定义的 C 函数,需要将其先编译成链接库,并将链接库所在路径加入到 LD_LIBRARY_PATH 中,需要使用 ffi.load 载入链接库
- 如果 ffi.load 第二个参数不填写,链接库以私有空间方式链入 Lua 脚本,使用时需要用 ffi.load 的返回值对函数进行调用
- 如果 ffi.load 第二个参数设置为 true,可以使用 ffi.C 直接调用,调用方法同 C 标准库函数的调用
Lua 处理 cdata 对象
上面对 Lua 如何调用 C 函数进行了小结,但是光能调用 C 函数是远远不够的,我们还需要对 C 的变量,变量类型进行处理。本节将对这部分进行探讨。
C 类型转化为 Lua 中的 ctype
C 类型转化为 Lua ctype,使用 ffi.typeof,该函数返回一个 ctype 变量类型
ctype = ffi.typeof(ct)
示例:
local ffi = require('ffi')ffi.cdef[[ struct s1 {int a;int b; }; typedef struct {int c;int d; } s2; union u {int a;long b;float c; }; enum e {Male,Female }; ]]print(ffi.typeof("int8_t")) print(ffi.typeof("uint8_t")) print(ffi.typeof("int16_t")) print(ffi.typeof("uint16_t")) print(ffi.typeof("int32_t")) print(ffi.typeof("uint32_t")) print(ffi.typeof("int64_t")) print(ffi.typeof("uint64_t")) print(ffi.typeof("double")) print(ffi.typeof("float")) print(ffi.typeof("bool")) print(ffi.typeof("struct s1")) print(ffi.typeof("s2")) print(ffi.typeof("union u")) print(ffi.typeof("enum e")) print(ffi.typeof("struct s1*")) print(ffi.typeof("struct s1[]"))
输出:
[root@AlexWoo-CentOS lua]# luajit ffit.lua ctype<char> ctype<unsigned char> ctype<short> ctype<unsigned short> ctype<int> ctype<unsigned int> ctype<int64_t> ctype<uint64_t> ctype<double> ctype<float> ctype<bool> ctype<struct s1> ctype<struct 98> ctype<union u> ctype<enum e> ctype<struct s1 *> ctype<struct s1 []>
创建并初始化 cdata 对象
使用 ctype 有以下两种构造 Lua C 对象的方法
cdata = ffi.new(ct [,nelem] [,init...]) cdata = ctype([nelem,] [init...])
基本类型 cdata 对象
首先是一个 C 的函数,我们使用构造的 cadata 对象来调用该函数:
int add(int x, int y) {return x+y; }
直接调用
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ int add(int x, int y); ]]print(t.add(10, 11))
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua 21
这种方法仅限于基本类型,lua 会将其基本类型转换为 cdata 的基本类型
使用 ffi.new 构造
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ int add(int x, int y); ]]ti = ffi.typeof("int") a = ffi.new(ti, 10) b = ffi.new("int", 11) print(type(a), type(b)) print(t.add(a, b))
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua cdata cdata 21
这里如果执行 print(ffi.typeof(“int”)),结果就是 ctype,因此这里 ffi.new 的第一个参数直接填为 “int” 与传入一个 ctype 的类型对象是等价的
使用类型对象构造
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ int add(int x, int y); ]]ti = ffi.typeof("int") a = ti(10) b = ti(11) print(t.add(a, b))
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua 21
基本类型指针 cdata 对象
首先是一个 C 的函数,我们使用构造的 cadata 对象来调用该函数:
int addp(int *x, int *y) {return *x+*y; }
这里构造指针对象可以使用 ffi.new 和 类型构造两种方法,下面只以一种进行举例,其它举一反三
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ int add(int x, int y); int addp(int *x, int *y); ]]a = ffi.new("int[1]", {10}) b = ffi.new("int[1]", {10}) print(t.addp(a, b))
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua 21
没有将 Lua 原生类型直接转换为指针类型的方法(至少我没找到),这里使用的是将 Lua 的 table 转为只有一个元素的数组,并将数组当作指针类型参数传入 addp 中
结构类型 cdata 对象
首先是一个 C 程序,我们使用构造的 cadata 对象来调用该函数:
#include <stdio.h>struct constr_t {int a;int b;struct innerstr {int x;int y;} c; };void print_constr_t(struct constr_t t) {printf("a:%d\n", t.a);printf("b:%d\n", t.b);printf("c.x:%d\n", t.c.x);printf("c.y:%d\n", t.c.y); }
Lua 程序
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ struct constr_t {int a;int b;struct innerstr {int x;int y;} c; }; void print_constr_t(struct constr_t t); ]]a = ffi.new("struct constr_t", {1, 2, {10, 11}}) t.print_constr_t(a)
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua a:1 b:2 c.x:10 c.y:11
这里我们看到构造一个 C 的结构类型与基本类型的方法基本类似,唯一区别就是需要使用 table 来进行构造,table 的层次结构与 C 的结构的层次必须符合
结构类型指针 cdata 对象
在日常使用中,对于结构体,我们更常使用的是指针。和基本类型指针 cdata 对象不同,可以直接使用与结构类型 cdata 对象相同的方式来构造结构类型指针的 cdata 对象
C 程序
#include <stdio.h>struct constr_t {int a;int b;struct innerstr {int x;int y;} c; };void print_pconstr_t(struct constr_t *t) {printf("a:%d\n", t->a);printf("b:%d\n", t->b);printf("c.x:%d\n", t->c.x);printf("c.y:%d\n", t->c.y); }
Lua 程序
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ struct constr_t {int a;int b;struct innerstr {int x;int y;} c; }; void print_pconstr_t(struct constr_t *t); ]]a = ffi.new("struct constr_t", {1, 2, {10, 11}}) t.print_pconstr_t(a)
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua a:1 b:2 c.x:10 c.y:11
字符串 cdata 对象
可以使用 Lua string 对象来初始化字符串 cdata 对象
C 程序
void print(const char *s) {printf("%s\n", s); }
Lua 程序
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ void print(const char *s); ]]a = ffi.new("const char*", "Hello World") t.print(a)
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua Hello World
注意对字符串,ffi.new 第一个参数只能是 const char *、const char[size] 或 char[size],不能是 char *,const char[?] 等类型
使用 cdata 对象
本节将探讨在 Lua 中怎么使用 cdata 对象
C 程序
#include <stdio.h>struct constr_t {int a;int b;struct innerstr {int x;int y;} c; };void print_pconstr_t(struct constr_t *t) {printf("a:%d\n", t->a);printf("b:%d\n", t->b);printf("c.x:%d\n", t->c.x);printf("c.y:%d\n", t->c.y); }int print_i(int x) {printf("x: %d\n", x); }int print_pi(int *px) {printf("px: %d\n", *px); }void print(const char *s) {printf("%s\n", s); }
Lua 程序
local ffi = require('ffi') local t = ffi.load("t", true)ffi.cdef[[ struct constr_t {int a;int b;struct innerstr {int x;int y;} c; }; void print_pconstr_t(struct constr_t *t); int print_i(int x); int print_pi(int *px); void print(const char *s); ]]ti = ffi.new("int", 10) tpi = ffi.new("int[1]", {20})ts = ffi.new("struct constr_t", {1, 2, {3, 4}})tcstr = ffi.new("const char*", "Hello World") tstr = ffi.new("char[11]", "Hello World")t.print_i(ti) --t.print_pi(ti) --luajit: ffit.lua:29: bad argument #1 to 'print_pi' (cannot convert 'int' to 'int *')--t.print_i(tpi) --luajit: ffit.lua:31: bad argument #1 to 'print_i' (cannot convert 'int [1]' to 'int') t.print_pi(tpi)t.print_pconstr_t(ts)t.print(tcstr) t.print(tstr)--对基本类型操作 ti = 100 --change tpi to number tpi[0] = 21 --tpi=22 --change tpi to number --tpi[1] = 2000 --luajit: ffit.lua:44: attempt to index global 'tpi' (a number value) print(type(ti), type(tpi)) t.print_i(ti) t.print_pi(tpi)--对 struct 类型操作 ts.b = 100 ts.c.y = 1000 print(type(ts)) t.print_pconstr_t(ts)--对字符串类型操作 --tcstr[2] = 32 --luajit: ffit.lua:54: attempt to write to constant location tstr[2] = 32 t.print(tstr)t.print("Hello Lua")
执行结果
[root@AlexWoo-CentOS lua]# luajit ffit.lua x: 10 px: 20 a:1 b:2 c.x:3 c.y:4 Hello World Hello World number cdata x: 100 px: 21 cdata a:1 b:100 c.x:3 c.y:1000 He lo World Hello Lua
从上面的例子可以看出,对基本类型,实际上不需要将其转为 cdata 类型;对于基本类型指针,操作方式与数组类似,在 Lua 中可当作 table 数组进行处理;对结构类型,在 Lua 中可当作 table 字典进行处理;对字符串,在 Lua 中可当作 table 数组进行处理
本节小结
- Lua 可以使用 ffi.new 初始化一个 cdata 对象,也可以使用 ffi.typeof 生成的类型来初始化一个 cdata 对象
- 对于基本类型和字符串类型,没有必要将其转为 cdata 对象,其可以作为参数传入 C 函数中。也可以接收 C 函数的返回值
- 对于基本类型指针对象,可以使用单元素数组进行初始化,可以使用数组元素赋值的方式改变其中的值
- 对于结构类型,可以传入 C 指针参数,也可以传入 C 普通参数。对结构类型的操作,与 table 的字典操作类似
luajit ffi 小结相关推荐
- luajit日记-FFI库
2019独角兽企业重金招聘Python工程师标准>>> LuaJIT FFI LibraryThe FFI library allows calling external C fun ...
- OpenResty LuaJIT和lua-resty-core(FFI vs Lua CFunction)介绍
LuaJIT 和 OpenResty lua-resty-core 1. LuaJIT 1.1 LuaJIT性能 1.2 LuaJIT FFI 1.3 table 的相关函数 1.4 避免使用 NYI ...
- luajit开发文档中文版(二)LuaJIT扩展
2022年6月10日15:33:04 luajit开发文档中文版(一)下载和安装 luajit开发文档中文版(二)LuaJIT扩展 luajit开发文档中文版(三)FAQ 常见问题 luajit开发文 ...
- luajit开发文档wiki中文版(二) LuaJIT 扩展
2022年6月9日09:39:53 luajit开发文档中文版(一)下载和安装 luajit开发文档中文版(二)LuaJIT扩展 luajit开发文档中文版(三)FAQ 常见问题 luajit开发文档 ...
- ngx_lua应用最佳实践
引子: 以下文字,是UPYUN系统开发工程师timebug在SegmentFault D-Day南京站技术沙龙上所做分享的内容要义提炼,主题为UPYUN系统开发团队在进行业务逻辑由C模块到ngx_lu ...
- UPYUN CDN 高可用架构实践
10 月 22 日,2015 全国架构师大会(SACC)在北京新云南皇冠假日酒店盛大召开,来自全国各地的逾 2000 名开发者参加大会.今天 ,UPYUN 架构师张聪受邀出席了会议,并做了关于 UPY ...
- Openresty 学习笔记(一)opm 工具的使用
1.自1.11.2.2开始,OpenResty版本已经包含并默认安装opm.所以通常你不需要自己安装opm. 2.我们在这里只需要做一个软连接就可以了 cd /usr/local/openresty/ ...
- 为什么你应该在 OpenResty 项目中使用 lua-resty-core
lua-resty-core 是什么? lua-resty-core 是 OpenResty 组件的一部分.它由两部分组成,一部分是 resty.core.*,提供了对 lua-nginx-modul ...
- 学会这27种编程语言,你还怕找不到女朋友?!那是要几个有几个!
我就知道你们会点进来看对不对,为什么我会这么说呢?看完以下内容再私信小编,小编就告诉你. 27 种语言: 过程型编程语言: C, Rust, Cython 面向对象数据建模语言: Java, C#, ...
最新文章
- 第十六届全国大学生智能车竞赛线上比赛(广东+西南科技大学)成绩排名与获奖信息
- pcb入门之原理图的绘制
- Consul 服务注册中心
- opencv 读取CV_16U图像 c++
- 电脑吃鸡按键详细_一秒八连击的即装即用吃鸡神器-飞智蜂刺手游按键体验
- 成长的勇气:一位IT人的辞职
- apache2配置rewrite_module
- 小一寸照片的尺寸规格 小一寸的照片多少像素
- Franka Emika机械臂快速入门教程
- 缠中说禅形态挖掘之九笔形态
- java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context
- 一根网线实现两台计算机网络共享
- bezier.CSS_SVG_canvas画_贝兹曲线
- 人工智能应用的细分领域有哪些
- 机器学习---决策树
- xshell安装及使用
- android apk反编译(获取源码,资源文件等)
- 【greenplum】greenplum pg_largeobject 大对象处理实践
- 从浏览器跳转到前端框架的路由实现
- Linux Shell 脚本编程 入门