原创作品,转载请注明来源是CSDN:http://blog.csdn.net/relar/article/details/38084689
开发游戏服务器往往有“热更新”的需求,就是在不停止服务程序的情况下,对服务程序进行升级。这里采用lua脚本桥接C++的模式。程序主框架用C++,程序的业务逻辑也是C++(具体的是C++写的DLL),这两者之间用LUA脚本语言进行桥接。当程序运行时,只要改变LUA脚本,即可以选择使用不同的DLL,以实现业务逻辑的升级更新。
上演示代码,代码分为三部分,第一部分是主程序:
//本例演示了lua调用DLL
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <conio.h>
#include "include\lua.hpp"
int _tmain(int argc, _TCHAR* argv[])
{
int global_var1 = 0;
printf("这个程序演示Lua调用C++的Dll:\n");
lua_State *pLuaState = luaL_newstate(); //也可以用lua_open();
luaL_openlibs(pLuaState);
if (luaL_dofile(pLuaState, "main2.lua"))// 加载脚本文件
{
printf("dofile error.\n");
}
_getch();
if (luaL_dofile(pLuaState, "main2.lua"))// 第二次加载脚本文件
{
printf("dofile error.\n");
}
_getch();
lua_close(pLuaState);
return 0;
}#include "my.h"
int GameLogic1(lua_State *L)
{
int n = lua_gettop(L);
double sum = 0;
int i;
for (i = 1; i <= n; i++)
{
sum += lua_tonumber(L, i);
}
lua_pushnumber(L, sum / n);
lua_pushnumber(L, sum);
return 2;
}
const struct luaL_Reg Func1lib[] = {
{ "GameLogic1", GameLogic1 },
{ NULL, NULL }
};
int luaopen_Func1lib(lua_State* L)
{
luaL_openlib(L, "Func1lib", Func1lib, 0);
return 1;
}#include "include\lua.hpp" #pragma comment(lib, "lua5.1.lib") #if defined(_WIN32) extern "C" _declspec(dllexport) int luaopen_Func1lib(lua_State* L); #else extern "C" int luaopen_Func1lib(lua_State* L); #endif
下面是LUA脚本:
local testlib = package.loadlib("E://Func1.dll", "luaopen_Func1lib")
print(testlib)--, "Can not open testlib.")
if(testlib)then
testlib(); --调用DLL中抛出函数
a,b=Func1lib.GameLogic1(6,6)
print("average:",a,"sum:",b);
a,b=Func1lib.GameLogic2(3,6)
print("average:",a,"sum:",b);
else
print("Error")
end另外我按照Func1.dll又写一个Func2.dll,内容稍有不同(这里就不必上代码了哈),演示的时候主程序执行了第一次加载脚本后会等待用户输入任意键,此时可以把脚本改为使用Func2.dll,再输入任意键让程序继续运行,业务逻辑就改了。
还有人是把业务逻辑以纯LUA实现,但是LUA自身功能有限,它生来就是用来调用或被C/C++调用的。
lua调用C++写的DLL实现“热更新”,布布扣,bubuko.com
原文:http://blog.csdn.net/relar/article/details/38084689