LuaJIT 比 官方 Lua 解释器运行更快,功能更强,只是有些库可能不兼容。
闲来无事,试用 LuaJIT FFI 测试 Windows 系统原生代码如下:
- local ffi = require("ffi")
- ffi.cdef[[
- int MessageBoxA(void *h, const char *txt, const char *title, int type);
- int GetSystemDirectoryA(char *buf, int len);
- void * malloc(int n);
- void free(void *p);
- int ShellExecuteA(void *w, const char *Operation, const char *File, const char *Param, const char *Dir, int nShowCmd);
- int GetWindowThreadProcessId(void *hWnd, int *lpdwProcessId);
- typedef struct {int hProcess, hThread, dwProcessId, dwThreadId;} PROCESS_INFORMATION;
- typedef struct {int cb; void *lpReserved, *lpDesktop, *lpTitle; int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags; uint16_t wShowWindow; uint16_t cbReserved2; uint8_t *lpReserved2; int hStdInput, hStdOutput, hStdError; } STARTUPINFO, *LPSTARTUPINFO;
- bool CreateProcessA(const char *lpApplicationName, const char *lpCommandLine, void *lpProcessAttributes, void *lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, void *lpEnvironment, const char *lpCurrentDirectory, STARTUPINFO *lpStartupInfo, PROCESS_INFORMATION *lpProcessInformation);
- int OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
- int WaitForSingleObject(int hdl, int ms);
- ]]
- local shlapi = ffi.load("shell32")
- local p = ffi.gc(ffi.C.malloc(255), ffi.C.free)
- local l = ffi.C.GetSystemDirectoryA(p, 255)
- ffi.C.MessageBoxA(nil,p,string.format("%d",l),16)
- print (string.format("%d", shlapi.ShellExecuteA(nil, nil, "notepad", nil, nil, 1)))
- local si = ffi.new("STARTUPINFO")
- local pi = ffi.new("PROCESS_INFORMATION")
- si.cb = ffi.sizeof(si)
- print (si.cb)
- if not ffi.C.CreateProcessA(nil, "notepad d:\\menu.lst", nil, nil, false, 0, nil, nil, si, pi) then
- print ("error")
- exit (0)
- end
- -- INFINITE 0xFFFFFFFF
- -- WAIT_OBJECT_0 0
- -- WAIT_ABANDONED_0 128
- -- WAIT_TIMEOUT 258
- -- SYNCHRONIZE 0x100000L
- local hsync = ffi.C.OpenProcess(0x100000, false, pi.dwProcessId)
- print ("wait for PID=" .. pi.dwProcessId .. " end: " .. ffi.C.WaitForSingleObject(hsync, -1))
复制代码 |