linux-lua_调用自定义so动态库(skynet)
最近看的 skynet 使用的 c+lua 的架构,框架提供的是基础的api,所以业务逻辑还得自己去写,如果某些业务逻辑比较耗性能,那可能就需要把某些业务逻辑丢到 c/c++ 去做,提供个接口供 lua 调用。
那么就需要去编个动态库(.so)、静态库(.a)啥的
写c接口(有些类型不严谨,就偷懒不改了,编译时会warning,可无视)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21CC ?= 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)
1
2
3
4
5
6
7
8
9
10
11function 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
结果1
2
3
4
5lua mylua.lua
-----testmyCustomLib
---ltest1,num:123
---ltest2,msg:helloworld,len:11
---ltest3,num:456,msg:yangx,len:5