Linux下编写Lua扩展so文件和调用方法实例
代码如下:
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <limits.h> #include <math.h> #include "lua.h" #include "lualib.h" #include "lauxlib.h" /* 库 open 函数的前置声明 */ int luaopen_mylib(lua_State *L); static int l_sin (lua_State *L) { double d = luaL_checknumber(L, 1); lua_pushnumber(L, sin(d)); //printf("ok now is luahook!\n"); return 1; /* number of results */ } static const luaL_Reg mylib[] = { {"lsin", l_sin}, {NULL, NULL} /* 必须以NULL结尾 */ }; int luaopen_mylib(lua_State *L) { luaI_openlib(L, "mylib", mylib, 0); return 1; }
如果是.cpp文件,在luaopen_mylib一定要加 extern "C", 否则导出的函数会被重命名,切记切记
编译:gcc mylibs.c -fPIC -shared -o libmylib.so -llua
代码如下:
Makefile文件 CXX =gcc LIBNAME:=libmylib.so HDRNAME:=mylibs.c TARGETNAME:=mylibs CNAME:=$(patsubst %,%.c,$(TARGETNAME)) ONAME:=$(patsubst %,%.o,$(TARGETNAME)) all:libmylib libmylib: $(ONAME) $(CXX) -g -shared -Wl,$(LIBNAME) \ -o $(LIBNAME) $(ONAME) -llua %.o: %.c $(CXX) -fPIC -c -Wall $(CNAME)clean:$(RM) *.o *.so
lua调用脚本:
代码如下:
local one, two, three = package.loadlib("libmylib.so", "luaopen_mylib")() print(mylib.lsin(10))
相关推荐
峰哥 2020-09-23
陈云佳 2020-08-15
wqiaofujiang 2020-07-05
wordmhg 2020-06-26
wqiaofujiang 2020-06-16
zllbirdonland 2020-06-16
eroshn 2020-06-10
长安长夜Saint 2020-06-07
Dawnworld 2020-06-07
fansenjun 2020-03-01
CSDNMrWang 2020-05-11
Dawnworld 2020-05-05
陈云佳 2020-04-21
Neptune 2020-04-20
shunelly 2020-04-16
aolishuai 2020-04-15
YukiRain 2020-04-14
陈云佳 2020-03-07
陈云佳 2020-03-05