(原+译)LUA调用C函数

转载请注明出处:

http://www.cnblogs.com/darkknightzh/p/5804924.html

原始网址:

http://www.troubleshooters.com/codecorn/lua/lua_lua_calls_c.htm

1. 新建hellofunc.c,输入:

 1 /* hellofunc.c (C) 2011 by Steve Litt
 2  * gcc -Wall -shared -fPIC -o Cfunc.so -I/usr/include/lua5.1 -llua5.1 hellofunc.c
 3  * Note the word " Cfunc " matches the string after the underscore in
 4  * function luaopen_ Cfunc(). This is a must.
 5  * The -shared arg lets it compile to .so format.
 6  * The -fPIC is for certain situations and harmless in others.
 7  * On your computer, the -I and -l args will probably be different.
 8 */
 9 
10 #include <lua5.1/lua.h>                               /* Always include this */
11 #include <lua5.1/lauxlib.h>                           /* Always include this */
12 #include <lua5.1/lualib.h>                            /* Always include this */
13 
14 static int isquare(lua_State *L)               /* Internal name of func */
15 {              
16     float rtrn = lua_tonumber(L, -1);      /* Get the single number arg */
17     printf("Top of square(), nbr=%f\n",rtrn);
18     lua_pushnumber(L,rtrn*rtrn);           /* Push the return */
19     return 1;                              /* One return value */
20 }
21 static int icube(lua_State *L){                /* Internal name of func */
22     float rtrn = lua_tonumber(L, -1);      /* Get the single number arg */
23     printf("Top of cube(), number=%f\n",rtrn);
24     lua_pushnumber(L,rtrn*rtrn*rtrn);      /* Push the return */
25     return 1;                              /* One return value */
26 }
27 
28 
29 /* Register this file's functions with the
30  * luaopen_libraryname() function, where libraryname
31  * is the name of the compiled .so output. In other words
32  * it's the filename (but not extension) after the -o
33  * in the cc command.
34  *
35  * So for instance, if your cc command has -o power.so then
36  * this function would be called luaopen_power().
37  *
38  * This function should contain lua_register() commands for
39  * each function you want available from Lua.
40  *
41 */
42 int luaopen_Cfunc(lua_State *L){
43     lua_register(
44             L,               /* Lua state variable */
45             "testsquare",        /* func name as known in Lua */
46             isquare          /* func name in this file */
47             );  
48     lua_register(L,"testcube",icube);
49     return 0;
50 }

2. 在ubuntu的终端中生成.so:

gcc -Wall -shared -fPIC -o Cfunc.so hellofunc.c

说明luaopen_ XXX对应于上面-o后面的XXX.soXXX。供LUA代码中require“XXX”来调用。

3. 新建myLUA.lua,输入:

require("Cfunc")
print(testsquare(1.414213598))
print(testcube(5))

4. 终端中输入:

lua myLUA.lua

5. 结果:

说明:电脑上装了lua5.1和lua5.2.默认的是lua5.2.使用lua myLUA.lua后,提示:

经过查找,发现默认的是lua5.2。然后直接使用lua5.1 myLUA.lua后,显示的就是正确的结果(如果使用lua5.2 myLUA.lua,显示的就是上面的错误)。当然,如果装了torch,torch默认的也是5.1的话,使用th myLUA.lua后,也能显示正确的结果,如下:

posted on 2016-08-24 22:41  darkknightzh  阅读(795)  评论(0编辑  收藏  举报

导航