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
skr
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
2018-05-12 codeforce440C-Maximum splitting-规律题