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);
luaL_loadfile(L, "./lua1.lua" );
lua_pcall(L,0,0,0);
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)这种方式是可以调用的
|