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

9 篇文章 0 订阅

最近看的 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 ?= 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)


  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
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝶泳奈何桥.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值