写c接口(有些类型不严谨,就偷懒不改了,编译时会warning,可无视)#include
#include
#include
static int ltest1(lua_State *L) {
int num = luaL_checkinteger(L, 1);
printf("--- ltest1, num:%d\n", num);
return 0;
}
static int ltest2(lua_State *L) {
size_t len = 0;
const char * msg = luaL_checklstring(L, 1, &len);
printf("--- ltest2, msg:%s, len:%d\n", msg, len);
return 0;
}
static int ltest3(lua_State *L) {
size_t len = 0;
int num = luaL_checkinteger(L, 1);
const char * msg = luaL_checklstring(L, 2, &len);
printf("--- ltest3, num:%d, msg:%s, len:%d\n", num, msg, len);
return 0;
}
int luaopen_myLualib(lua_State *L) {
luaL_Reg l[] = {
{ "test1", ltest1 },
{ "test2", ltest2 },
{ "test3", ltest3 },
{ NULL, NULL },
};
luaL_newlib(L, l);
return 1;
}
写makefile文件
CC ?= gcc
CFLAGS = -g -O2 -Wall -I$(LUA_INC)
SHARED := -fPIC --shared
TARGET = myLualib.so
LUA_CLIB_PATH = clib
# 引入lua头文件
LUA_INC ?= /root/lua-5.3.0/src
start: $(TARGET)
$(TARGET) : myLualib.c | $(LUA_CLIB_PATH)
$(CC) $(CFLAGS) $(SHARED) $^ -o $@
clean:
rm -fr $(TARGET)
$(LUA_CLIB_PATH) :
mkdir $(LUA_CLIB_PATH)
执行以下make命令,注意target是start # make start然后myLualib.so就出来了
写个lua测试以下 (文件名 mylua.lua)
function test3( ... )
print("----- test myCustomLib")
package.cpath = "./?.so" --so搜寻路劲
local f = require "myLualib" -- 对应luaopen_myLualib中的myLualib
f.test1(123)
f.test2("hello world")
f.test3(456, "yangx")
end
test3()
执行以下 # lua mylua.lua结果 [root@localhosttestMake]# lua mylua.lua
-----testmyCustomLib
---ltest1,num:123
---ltest2,msg:helloworld,len:11
---ltest3,num:456,msg:yangx,len:5