Lua调用C++生成的DLL库
本文参考了某大佬的博客,写得十分详细,推荐!!!
需求:
在之前的求解器中添加了Lua库,使得程序可以在Lua脚本中实现自定义函数功能,考虑到未来可能需要与第三方程序库进行耦合计算,现在想到可以借助Lua脚本,在脚本中调用第三方动态库,以实现其功能的扩展。接下来将要简要记录下Lua中调用第三方库的实现过程。
编译Lua库
在windows平台下,借助mingw编译器进行编译。
首先需要去下载Lua源代码,这里下载的是最新的 Lua5.4
在安装路径下进行编译,源码中已经写好了Makefile,可以直接进行编译
mingw32-make mingw mingw32-make install local
在install目录下得到lua.exe,lua54.dll,liblua.a 等可执行文件,动态库与静态库
C++编写DLL接口
以下给出了一个示例,注释比较详细
cpp2dll.cpp
#include <Windows.h> #include "lua.hpp" #include <iostream> #include <time.h> #include <cmath> // 函数示例:参数输入顺序 int Lua_printf(lua_State *L) { int n = lua_gettop(L); // 判断输入参数个数 switch (n) { case 0: std