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

来源:互联网 发布:小米4没有4g网络设置 编辑:程序博客网 时间:2024/06/06 19:28

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

原创 2016年08月02日 13:34:00

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


  1. 写c接口(有些类型不严谨,就偷懒不改了,编译时会warning,可无视)
    [cpp] view plain copy
    1. #include <lua.h>  
    2. #include <lauxlib.h>  
    3. #include <stdio.h>  
    4.    
    5. static int ltest1(lua_State *L) {  
    6.     int num = luaL_checkinteger(L, 1);  
    7.     printf("--- ltest1, num:%d\n", num);  
    8.     return 0;  
    9. }  
    10.    
    11. static int ltest2(lua_State *L) {  
    12.     size_t len = 0;  
    13.     const char * msg = luaL_checklstring(L, 1, &len);  
    14.     printf("--- ltest2, msg:%s, len:%d\n", msg, len);  
    15.     return 0;  
    16. }  
    17.    
    18. static int ltest3(lua_State *L) {  
    19.     size_t len = 0;  
    20.     int num = luaL_checkinteger(L, 1);  
    21.     const char * msg = luaL_checklstring(L, 2, &len);  
    22.     printf("--- ltest3, num:%d, msg:%s, len:%d\n", num, msg, len);  
    23.     return 0;  
    24. }  
    25.    
    26. int luaopen_myLualib(lua_State *L) {  
    27.    
    28.     luaL_Reg l[] = {  
    29.         { "test1", ltest1 },  
    30.         { "test2", ltest2 },  
    31.         { "test3", ltest3 },  
    32.         { NULL, NULL },  
    33.     };  
    34.     luaL_newlib(L, l);  
    35.    
    36.     return 1;  
    37. }  


  2. 写makefile文件
    [cpp] view plain copy
    1. CC ?= gcc  
    2. CFLAGS = -g -O2 -Wall -I$(LUA_INC)  
    3. SHARED := -fPIC --shared  
    4.    
    5. TARGET = myLualib.so  
    6. LUA_CLIB_PATH = clib  
    7.    
    8. # 引入lua头文件  
    9.    
    10. LUA_INC ?= /root/lua-5.3.0/src  
    11.    
    12. start: $(TARGET)  
    13.    
    14. $(TARGET) : myLualib.c | $(LUA_CLIB_PATH)  
    15.     $(CC) $(CFLAGS) $(SHARED) $^ -o $@  
    16.    
    17. clean:  
    18.     rm -fr $(TARGET)  
    19.    
    20. $(LUA_CLIB_PATH) :  
    21.     mkdir $(LUA_CLIB_PATH)  


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

  4. 写个lua测试以下 (文件名 mylua.lua)
    [cpp] view plain copy
    1. function test3( ... )  
    2.     print("----- test myCustomLib")  
    3.     package.cpath = "./?.so" --so搜寻路劲  
    4.     local f = require "myLualib" -- 对应luaopen_myLualib中的myLualib  
    5.    
    6.     f.test1(123)  
    7.     f.test2("hello world")  
    8.     f.test3(456, "yangx")  
    9. end  
    10.    
    11. test3()  


    执行以下
    # lua mylua.lua结果

    [cpp] view plain copy
    1. [root@localhosttestMake]# lua mylua.lua   
    2. -----testmyCustomLib  
    3. ---ltest1,num:123  
    4. ---ltest2,msg:helloworld,len:11  
    5. ---ltest3,num:456,msg:yangx,len:5  
原创粉丝点击