這篇文章主要介紹了Linux下編寫Lua擴展so文件和調用方法實例,本文給出C語言代碼、編譯SO文件、Lua中調用代碼實例,需要的朋友可以參考下
代碼如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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))