(原+译)LUA调用C函数

时间:2023-03-09 22:37:15
(原+译)LUA调用C函数

转载请注明出处:

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

原始网址:

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

1. 新建hellofunc.c,输入:

 /* hellofunc.c (C) 2011 by Steve Litt
* gcc -Wall -shared -fPIC -o Cfunc.so -I/usr/include/lua5.1 -llua5.1 hellofunc.c
* Note the word " Cfunc " matches the string after the underscore in
* function luaopen_ Cfunc(). This is a must.
* The -shared arg lets it compile to .so format.
* The -fPIC is for certain situations and harmless in others.
* On your computer, the -I and -l args will probably be different.
*/ #include <lua5./lua.h> /* Always include this */
#include <lua5./lauxlib.h> /* Always include this */
#include <lua5./lualib.h> /* Always include this */ static int isquare(lua_State *L) /* Internal name of func */
{
float rtrn = lua_tonumber(L, -); /* Get the single number arg */
printf("Top of square(), nbr=%f\n",rtrn);
lua_pushnumber(L,rtrn*rtrn); /* Push the return */
return ; /* One return value */
}
static int icube(lua_State *L){ /* Internal name of func */
float rtrn = lua_tonumber(L, -); /* Get the single number arg */
printf("Top of cube(), number=%f\n",rtrn);
lua_pushnumber(L,rtrn*rtrn*rtrn); /* Push the return */
return ; /* One return value */
} /* Register this file's functions with the
* luaopen_libraryname() function, where libraryname
* is the name of the compiled .so output. In other words
* it's the filename (but not extension) after the -o
* in the cc command.
*
* So for instance, if your cc command has -o power.so then
* this function would be called luaopen_power().
*
* This function should contain lua_register() commands for
* each function you want available from Lua.
*
*/
int luaopen_Cfunc(lua_State *L){
lua_register(
L, /* Lua state variable */
"testsquare", /* func name as known in Lua */
isquare /* func name in this file */
);
lua_register(L,"testcube",icube);
return ;
}

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

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

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

3. 新建myLUA.lua,输入:

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

4. 终端中输入:

lua myLUA.lua

5. 结果:

(原+译)LUA调用C函数

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

(原+译)LUA调用C函数

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

(原+译)LUA调用C函数