分享

luajit FFI LUA脚本中怎样调用C自己定义的函数

 痛苦兔子 2015-07-10

C代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <luajit.h>
 
typedef struct foo { int a, b; } foo_t;
 
extern int test(int a);
extern int dofoo(foo_t *f, int n);
 
int test(int a)
{
  printf("a=%d\n", a);
 
  return 0;
}
 
int dofoo(foo_t *f, int n)
{
      foo_t foo = *f;
 
      printf("dofoo\n");
 
      printf("foo.a=%d,foo.b=%d\n", foo.a,foo.b);
 
      foo.a = 100;
      foo.b = 200;
 
      *f = foo;
 
      return 0;
}
 
int main(int argc, char *argv[]) {
      lua_State *L;
 
      L = luaL_newstate(); /*创建一个解释器句柄*/
      if (L == NULL) {
          printf("L is null1\n");
          return -1;
      }
 
      luaL_openlibs(L);             /*打开所有的Lua库*/
 
      luaL_loadfile(L,"./lua1.lua"); /*调入Lua脚本文件*/
 
      lua_pcall(L,0,0,0); /*执行Lua脚本*/
      lua_close(L);       /*关闭句柄*/
 
      return 0;
}



lua1.lua如下:

local ffi = require("ffi")

ffi.cdef[[
    int printf(const char *fmt, ...);
    typedef struct foo { int a, b; } foo_t;  // Declare a struct and typedef.
    int dofoo(foo_t *f, int n);  /* Declare an external C function. */
    int test(int a);
]]

ffi.C.printf("Hello %s!\n", "world")

local foo = ffi.new("foo_t")
foo.a = 10
foo.b = 20
ffi.C.printf("foo.a=%d\n", ffi.new("int", foo.a))
ffi.C.printf("foo.b=%d\n", ffi.new("int", foo.b))

ffi.C.testddf(new("int", 200))



我的想法就是在LUA中调用C代码中的test函数,不是用LUA C API的方式,是用LuaJIT的FFI库


把test函数编译成一个动态库方式,然后在lua中用ffi.load(libtest)这种方式是可以调用的

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章