1

I have compilied console host program written on c/c++ (i don't have sources). Host program have support for lua scripts (probably using lua virtual machine). Host program load lua libraries

luaopen_base luaopen_table luaopen_string luaopen_math luaopen_debug

and allow reloading all lua scripts.

Is it possible to call any host c/c++ function from lua script by function address (got them from external debugger in host program)?

Is it possible to load any C/C++ compilied libs from lua in this case and call its functions?

One man on other forum wrote this code for this question

// 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;
}

any ideas how use it in compilied host program?

user3309760
  • 175
  • 1
  • 6
  • Does the host program load Lua dynamically or is Lua linked statically into it? In the first case you can probably write your own "Lua" library and fool the host. – lhf Feb 14 '14 at 13:00

2 Answers2

3

The proper way to call C/C++ functions from Lua is to write interface code to exchange data on the Lua stack.

However there are extensions to allow direct call to functions in shared libraries (.dll or .so).

Have a look at the FFI Library (http://luajit.org/ext_ffi.html) or Alien Lua (http://alien.luaforge.net/) which uses the libffi library (http://www.sourceware.org/libffi/)

Remo.D
  • 16,122
  • 6
  • 43
  • 74
1

To access C/C++ functions in Lua you have to have them exposed via a certain api, Lua does not load "regular" dlls (or .so if you which) directly. Instead you have to have a intermediate library to expose to the Lua environment which C functions will be available.

Cheers

prmottajr
  • 1,816
  • 1
  • 13
  • 22