【问题标题】:How do i run an executeable with FFI in lua如何在 lua 中使用 FFI 运行可执行文件
【发布时间】:2020-07-20 14:45:03
【问题描述】:

由于我无法在我当前的项目中使用os.execute(),但我能够使用 LuaJIT 的 FFI 中的所有内容,而且我不懂 c/c++ 我想知道如何使用 ffi 执行和 .exe 文件

【问题讨论】:

  • FFI 用于访问二进制 C 库的方法,如 .dll 文件和 a.files。可以创建/查找打开外部程序的库
  • 但在其他说明中......也许 io.popen 可能是一个解决方案
  • 我也不能使用 io.open。

标签: windows winapi lua ffi


【解决方案1】:
local ffi = require("ffi")

ffi.cdef[[
typedef struct _STARTUPINFOA {
  uint32_t  cb;
  void *    lpReserved;
  void *    lpDesktop;
  void *    lpTitle;
  uint32_t  dwX;
  uint32_t  dwY;
  uint32_t  dwXSize;
  uint32_t  dwYSize;
  uint32_t  dwXCountChars;
  uint32_t  dwYCountChars;
  uint32_t  dwFillAttribute;
  uint32_t  dwFlags;
  uint16_t  wShowWindow;
  uint16_t  cbReserved2;
  void *    lpReserved2;
  void **   hStdInput;
  void **   hStdOutput;
  void **   hStdError;
} STARTUPINFOA, *LPSTARTUPINFOA;
typedef struct _PROCESS_INFORMATION {
  void **  hProcess;
  void **  hThread;
  uint32_t dwProcessId;
  uint32_t dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
uint32_t CreateProcessA(
  void *,
  const char * commandLine,
  void *,
  void *,
  uint32_t,
  uint32_t,
  void *,
  const char * currentDirectory,
  LPSTARTUPINFOA,
  LPPROCESS_INFORMATION
);
uint32_t CloseHandle(void **);
]]

local function execute(commandLine, currentDirectory)
   local si = ffi.new"STARTUPINFOA"
   si.cb = ffi.sizeof(si)
   local pi = ffi.new"PROCESS_INFORMATION"
   local ok = ffi.C.CreateProcessA(nil, commandLine, nil, nil, 0, 0, nil, currentDirectory, si, pi) ~= 0
   if ok then
      ffi.C.CloseHandle(pi.hProcess)
      ffi.C.CloseHandle(pi.hThread)
   end
   return ok  -- true/false
end

execute[["C:\WINDOWS\system32\notepad.exe" "some file.txt"]]

if not execute[["C:\Program Files\Microsoft Games\Minesweeper\MineSweeper.exe"]] then
   print"Can not find the game"
end

【讨论】:

  • 使用 thi 时出现以下错误,我无法自行修复:缺少符号“CreateProcessA”的声明
  • 这可能意味着你不能to use everything from LuaJIT's FFI 换句话说,你的 LuaJIT FFI 是沙盒的,WinAPI 是不可访问的。
  • 您可以尝试加载库local lib = ffi.load"kernel32" 并在任何地方使用lib.* 而不是ffi.C.*
  • 或者ffi.cdef 可能被故意替换为存根以禁用调用外部函数。
猜你喜欢
  • 2018-12-31
  • 2021-12-08
  • 2013-08-22
  • 2017-06-27
  • 2020-09-13
  • 2013-05-04
  • 1970-01-01
相关资源
最近更新 更多