luajit ffi 小结

luajit ffi 小结Luajitffi 接口使用小结 1 使用 Luajitffi 加载 C 链接库 2 使用 Luajitffi 调用 C 函数 3 使用 Luajitffi 处理基本类型对象 结构体对象 字符串对象 cdata4 cdata 赋值及修改本文仅限于使用 C 链接库 后面文章将介绍使用 Luajitffi 加载 C 链接库

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 
         
           ctype 
          
            ctype 
           
             ctype 
            
              ctype 
             
               ctype 
              
                ctype 
               
                 ctype 
                
                  ctype 
                 
                   ctype 
                  
                    ctype 
                   
                     ctype 
                    
                      ctype 
                     
                       ctype 
                      
                        ctype 
                       
                         ctype 
                        
                          ctype 
                          
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           
         
  • 创建并初始化 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; } 
      1. 直接调用
        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 的基本类型

      2. 使用 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 的类型对象是等价的

      3. 使用类型对象构造
        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 
             
               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 
             
               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 
         
           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 的字典操作类似
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/213846.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午5:31
下一篇 2026年3月18日 下午5:32


相关推荐

  • Manus AI:颠覆性创新还是工程优化?

    Manus AI:颠覆性创新还是工程优化?

    2026年3月15日
    3
  • C++和Java有哪些区别

    C++和Java有哪些区别1.C++创建对象后需要在使用结束后调用delete方法将其销毁,Java有垃圾回收机制,用来监视new出来的所有对象,辨别不会再被引用的对象,然后释放内存空间2.C++可以重载操作符,Java不能重载3.当变量作为类的成员使用时,Java才确保给定默认值,以确保那些基本类型的成员变量得到初始化,但是C++没有此功能4.C++有多继承,Java只有单继承5.Java中没有sizeof(),在C++中sizeof()操作符能够告诉我们为数据项分配的字节数,因为C++中不同的数据类型在不同的机器上可能有

    2022年7月9日
    18
  • openclaw页面无法访问解决方法

    openclaw页面无法访问解决方法

    2026年3月13日
    5
  • 软硬件版本号命名规范及原则是什么_文件版本号怎么编

    软硬件版本号命名规范及原则是什么_文件版本号怎么编1.软件版本阶段说明 Alpha版:此版本表示该软件在此阶段主要是以实现软件功能为主,通常只在软件开发者内部交流,一般而言,该版本软件的Bug较多,需要继续修改。 Beta版:该版本相对于α版已有了很大的改进,消除了严重的错误,但还是存在着一些缺陷,需要经过多次测试来进一步消除,此版本主要的修改对像是软件的UI。 RC版:该版本已经相当成熟了,基本上不存在导致错误的BUG,与即将发行的正式版相差无几。 Release版:该版本意味“最终版本”,在前面版本的一系列

    2025年10月20日
    4
  • 3322 动态域名更新 IP 程序补丁

    3322 动态域名更新 IP 程序补丁因为使用的是动态 IP 远程访问比较麻烦 所以一般会申请一个 3322 的动态域名 然后通过更新域名对应的 IP 来实现域名访问远程主机的目的 在 linux 下 3322 的网站提供了用 lynx 来更新 IP 的命令 但是不知从何时开始 这命令已经不好使了 输出的错误如下 lynx nbsp mime header nbsp auth xxxx xxxx http www 3322 org dyn

    2026年3月19日
    2
  • Java Calendar 日历类的时间操作 Timestamp Date Calendar 相互转换

    Java Calendar 日历类的时间操作 Timestamp Date Calendar 相互转换JavaCalendar日历类的时间操作,这也许是Java环境下创建和管理日历及操作时间最简单的一个方案了,示范代码也很简单。演示了获取时间,日期时间的累加和累减,以及日期时间的比较。原文地址:blog.csdn.net/joyous/article/details/9630893注意事项:Calendar的month从0开始,也就是全年12个月由0~1…

    2022年4月26日
    59

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号