Lua调用C程序以及so程序

这篇博客介绍了lua代码调用C程序代码的方式。
https://chsasank.com/lua-c-wrapping.html

总结:

在C代码中需要引入lua状态机等库函数,并填写接口到函数的映射关系。

编译该C代码文件,生成so包后,lua就能引入相关包。

对于sinTest.c代码文件(内容如下所示),通过如下命令生成so包:

gcc sinTest.c -shared -o mylib.so -fPIC -I/usr/include/lua5.3 -llua5.3

然后在lua中就能调用相关的so动态库了。

当然,这样的实现不够优雅,每个函数都要手动解析Lua传递过来的参数;而对于C++中的类则不够方便封装了。

而解决上述两个问题的一个方法,是通过Swig


#ifdef __cplusplus
  #include "lua.hpp"
#else
  #include "lua.h"
  #include "lualib.h"
  #include "lauxlib.h"
#endif
#include <math.h>

//so that name mangling doesn't mess up function names
#ifdef __cplusplus
extern "C"{
#endif

static int c_swap (lua_State *L) {
    //check and fetch the arguments
    double arg1 = luaL_checknumber (L, 1);
    double arg2 = luaL_checknumber (L, 2);

    //push the results
    lua_pushnumber(L, arg2);
    lua_pushnumber(L, arg1);

    //return number of results
    return 2;
}

static int my_sin (lua_State *L) {
    double arg = luaL_checknumber (L, 1);
    lua_pushnumber(L, sin(arg));
    return 1;
}

//library to be registered
static const struct luaL_Reg mylib [] = {
      {"c_swap", c_swap},
      {"mysin", my_sin}, /* names can be different */
      {NULL, NULL}  /* sentinel */
    };

//name of this function is not flexible
int luaopen_mylib (lua_State *L){
    luaL_newlib(L, mylib);
    return 1;
}

#ifdef __cplusplus
}
#endif
posted @ 2024-05-12 23:52  ckxkexing  阅读(33)  评论(0编辑  收藏  举报