从另一个应用程序访问lua_State

问题描述

现在假设您有两个具有不同lua实例的程序。一个是主程序,第二个是您为其编写的dll。

在我的问题中,我将从现在开始将主程序命名为main,dll。我们将孩子加载到Main进程中,绕开它并以某种方式访问​​lua_State。

我的主要问题是,可以在运行主程序时通过抓取的lua_State进行lua_pcall或dofile吗?

示例代码

主程序:

#include <lua.hpp>

bool loadFile(lua_State* L) {
    // run the Lua script
    luaL_dofile(L,"helloworld.lua");
    if (lua_pcall(L,eh) != 0)
    {
        std::string err = luaL_checkstring(L,-1);
        lua_pop(L,1);
    }

}

int main()
{
    // create new Lua state
    lua_State *lua_state;
    lua_state = luaL_newstate();

    loadFile(lua_state);
}

子程序:

#include <lua.hpp>
#include "hookingLibrary.h" 

typedef int(__fastcall* main_loadFile_Proto)(lua_State* L);
main_loadFile_Proto main_loadFile_Ptr;

lua_State * L lastState;
uint64_t main_loadFile_Addr = 0x0; 

int main_loadFile_Detour(lua_State* L) { 
    lastState = L;
    return main_loadFile_Ptr(L);
}

int main()
{
    // detouring etc.
    // I do not put detouring codes here. I am just declaring it as an 
    // opinion.
    
    HookingLibrary::hook((LPVOID)(uintptr_t)main_loadFile_Addr,&main_loadFile_Detour,(LPVOID*)&main_loadFile_Ptr);

    do{ 
       Sleep(100);
    }while(!lastState);

 
    // create new Lua state
    lua_State *lua_state;
    lua_state = lastState;

  
    // run the Lua script
    luaL_dofile(lua_state,"helloworld.lua");

    // close the Lua state
    lua_close(lua_state);
}

解决方法

Now imagine you have two programs with different lua instances. One is the main program,the second is the dll you coded for it.

此陈述不是很清楚,取决于您的期望。我看到2个可能的答案。

  1. 创建一个实现Lua某些附加功能的DLL。 DLL库可以在以后由主程序使用。在这种情况下,只有1个lua_state实例,只有1个Lua解释器。这个Lua解释器可以由DLL或由主要功能创建。

DLL的接口是这样的:

#ifndef DLL_AUGMENTED
#define DLL_AUGMENTED

#include "lua.h"

lua_State *DLL_CreateAugmentedLuaInterpreter ();
void       DLL_FreeLuaInterpreter ();

#endif

并且可以被main使用:

#include "lua-augmented.h"

int main (int argc,char **argv)
{
  lua_State *LuaState = DLL_CreateAugmentedLuaInterpreter ();

  // TODO: use the augmented Lua instance

  DLL_FreeLuaInterpreter(LuaState);

  return 0;
}
  1. 需要有两个Lua实例,如One is the main program,the second is the dll所示。在这种情况下,这更加困难,因为需要使用IPCsockets来实现pipes进程间通信。最好是寻找LuaSocket库。

Interprocess communication in Lua with Example?