Linux环境下 lua 调用自定义so动态库(skynet)

来源:互联网 发布:深圳壹柒捌网络怎么样 编辑:程序博客网 时间:2024/05/23 11:59

最近看的 skynet 使用的 c+lua 的架构,框架提供的是基础的api,所以业务逻辑还得自己去写,如果某些业务逻辑比较耗性能,那可能就需要把某些业务逻辑丢到 c/c++ 去做,提供个接口供 lua 调用。
那么就需要去编个动态库(.so)、静态库(.a)啥的


  1. 写c接口(有些类型不严谨,就偷懒不改了,编译时会warning,可无视)
    #include <lua.h>#include <lauxlib.h>#include <stdio.h> 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;}


  2. 写makefile文件
    CC ?= gccCFLAGS = -g -O2 -Wall -I$(LUA_INC)SHARED := -fPIC --shared TARGET = myLualib.soLUA_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)


  3. 执行以下make命令,注意target是start
    # make start然后myLualib.so就出来了

  4. 写个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


0 0
原创粉丝点击