luajit的ffi更快的原因_lua return

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


Jetbrains全系列IDE稳定放心使用

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

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

赞 (0)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • spark报错OutOfMemory「建议收藏」

    最近在使用spark进行分析的时候几千万的数据量感觉不多但是跑起来非常慢内存溢出OutOfMemory1.然后在有使用map的地方在map之前进行分区repartition2.join会有shuffle产生shuffle也会产生数据溢出3.map也可以换成 mapPartitions并且适当调整分区数200400 其他的还有很多我用的就这些然后任务可以跑出来。…

    2022年4月16日
  • position属性值有哪些_静态web和动态web的区别

    position属性值有哪些_静态web和动态web的区别1:static静态定位,是默认值,当代码使用top,left.等,无效2:absolute绝对定位,相对于父元素进行定位,元素通过top,right,left等进行定位3:fixed

    2022年8月1日
  • docker command not found_阿里云socket连接数

    docker command not found_阿里云socket连接数背景介绍阿里云提醒,服务器需由经典网络迁移至专有网络,迁移完成,启动服务时,原本已经运行了几个月的脚本,报错 10049。127.0.0.1测试无误,ping公网IP也没毛病,百思不得姐。解决方法各方查证,结论如下:阿里云有两种网络①经典网络②专有网络经典网络可以直接绑定公网IP,专有网络绑定公网IP??不好意思,不行!!why???客服是这么讲的“这不是经典网…

    2022年10月1日
  • 搜索,推荐,广告系统架构及算法技术资料大合集吐血整理——2020年终分享

    搜索,推荐,广告系统架构及算法技术资料大合集吐血整理——2020年终分享算法学习资料:AI_Tutorial各大厂架构开发学习资源;精华机器学习,NLP,图像识别等人工智能领域学习资料,搜索,推荐,广告系统架构及算法技术资料吐血整理你还在为学习算法摸不着头脑么?你还在为技术调研各种Google么?AI的牛b吹不上去?盯紧了,这里就是你的2020女朋友~。本项目会持续关注AI落地的一些优质技术资料。大家也可以去网站投稿。算法学习资料:AI_Tutorial…

    2022年6月2日
  • python numpy教程_python读取图片尺寸

    python numpy教程_python读取图片尺寸pythonnumpy图片pad参数详解

    2022年8月13日
  • 约瑟夫环 OJ

    约瑟夫环 OJ循环链表的应用,并且应为不带头节点的循环链表,首先创建一个循环链表,在函数JOHEPHUS中进行操作,主要就是用for找到要删除的元素(注意p==1单独考虑,for中p至少为2),删除元素并输出直至链表为空。for(j=1;j&lt;=p-1;j++)把寻找报数的位置和寻找要删除的节点的前驱结合在一个循环中,减少时间复杂度,因为第一次写我是在主函数中用r指向找到的要删除的节点,然后传入de…

    2022年5月29日

发表回复

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

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