我編寫了c/C++編寫的控制檯主機程序(我沒有源代碼)。主機程序支持lua腳本(可能使用lua虛擬機)。主機程序加載Lua庫是否可以通過函數地址從lua腳本中調用任何主機c/C++函數?
luaopen_base luaopen_table luaopen_string luaopen_math luaopen_debug
,並允許重裝所有的Lua腳本。
是否可以通過函數地址從lua腳本調用任何主機c/C++函數(在主機程序中從外部調試器獲取它們)?
在這種情況下是否可以從lua載入任何C/C++編譯的庫並調用它的函數?
一個人在其他論壇上寫下此代碼爲這個問題
// re = callClientFunction(addr, { args }, 'cdecl')
// re = callClientFunction(method, { obj, arg1 }, 'this')
// re = callClientFunction(0x08, { obj, arg1 }, 'this') = obj->vtable[2]->(arg1)
inline int callCdeclFunction(lua::State* L, uintptr_t addr, const std::vector<lua::Integer>& args)
{
typedef lua::Integer __cdecl cf0();
typedef lua::Integer __cdecl cf1(lua::Integer);
typedef lua::Integer __cdecl cf2(lua::Integer, lua::Integer);
typedef lua::Integer __cdecl cf3(lua::Integer, lua::Integer, lua::Integer);
typedef lua::Integer __cdecl cf4(lua::Integer, lua::Integer, lua::Integer, lua::Integer);
typedef lua::Integer __cdecl cf5(lua::Integer, lua::Integer, lua::Integer, lua::Integer, lua::Integer);
lua::Integer re = 0;
switch(args.size())
{
case 0: re = reinterpret_cast<cf0*>(addr)(); break;
case 1: re = reinterpret_cast<cf1*>(addr)(args[0]); break;
case 2: re = reinterpret_cast<cf2*>(addr)(args[0], args[1]); break;
case 3: re = reinterpret_cast<cf3*>(addr)(args[0], args[1], args[2]); break;
case 4: re = reinterpret_cast<cf4*>(addr)(args[0], args[1], args[2], args[3]); break;
case 5: re = reinterpret_cast<cf5*>(addr)(args[0], args[1], args[2], args[3], args[4]); break;
default:
luaL_error(L, "%s: too many args (max %d, provided %d).\n", __func__, 5, args.size());
}
return re;
}
任何想法如何在compilied主機程序使用它呢?
是否主機程序加載的Lua動態或者Lua的靜態鏈接到它?在第一種情況下,你可以編寫自己的「Lua」庫並欺騙主機。 – lhf