Linux下编写Lua扩展so文件和调用方法实例
程序员文章站
2022-06-24 11:52:49
复制代码 代码如下:
#include
#include
#include
#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>
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))
复制代码 代码如下:
#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))
上一篇: Lua中..和#运算符的使用方法
下一篇: Lua教程(二十二):userdata