前提:
需要下载lua源代码,并且获取 lua.lib文件
有些lua的源代码已经编译过了,附带lib文件,可直接用;
如果没有,可以看这篇文章:静态库编译
一、dll 项目创建及项目属性设置
查看我的另一篇文章,创建及属性设置都一样。
vs2022编译c 动态库,以及调用
二、c++ dll 代码
这里生成一个可以获取随机数的dll
#include<Windows.h>
#include "lua.hpp"
#include<iostream>
#include<time.h>
#pragma comment(lib, "luaLib.lib") // 这里需要lua的静态库,否则lua api 无法被调用
//static inline double timeout_gettime(void) {
// FILETIME ft;
// double t;
// GetSystemTimeAsFileTime(&ft);
// /* Windows file time (time since January 1, 1601 (UTC)) */
// t = ft.dwLowDateTime / 1.0e7 + ft.dwHighDateTime * (4294967296.0 / 1.0e7);
// /* convert to Unix Epoch time (time since January 1, 1970 (UTC)) */
// return (t - 11644473600.0);
//}
static int getRand(lua_State* L) {
int n = lua_gettop(L);
double a, b, temp;
srand(time(NULL));
if (n == 0) {
a = 0;
b = time(NULL);
}
else if(n == 1) {
a = 0;
b = lua_tonumber(L, -1);
lua_pop(L, -1);
}
else {
a = lua_tonumber(L, -1);
b = lua_tonumber(L, -1);
lua_pop(L, -1);
lua_pop(L, -1);
if (a > b) {
temp = a;
a = b;
b = temp;
}
}
int randValue = rand() % int(b - a + 1) + a;
lua_pushnumber(L, randValue); // 返回结果需要入栈
return 1; // 执行成功,返回一
}
// 注册结构
static const luaL_Reg m_funcs[]{
{"getRand", getRand},
{NULL, NULL}
};
// 注册函数【luaopen_xxx 必须是 dll的名称,即 xxx.dll】
extern "C" int __declspec(dllexport) luaopen_cppdll2(lua_State *L) {
luaL_newlib(L, m_funcs); // 创建一个新表,并将函数入栈
return 1;
}
注:直接点:
菜单:生成->生成xxxdll
三、lua代码编写
local cppdll2 = require "cppdll2" // 这个就是导出dll名称,为了防止获取失败,新手建议直接把lua放dll同目录下
print(cppdll2.getRand()) // 直接调用随机值函数
print(cppdll2.getRand(10)) // 直接调用随机值函数
print(cppdll2.getRand(10, 100)) // 直接调用随机值函数
注意:
一定要确保lua.exe 的版本和 生成dll用到的头文件 和 lib文件 版本一致,不然会执行失败!!!