Lua 5.1 標準 package.loadlib 僅能載入符合 Lua C API 規範的擴充庫。若需呼叫通用 DLL (如 msvcrt.dll),需使用 alien 套件,它提供 FFI (Foreign Function Interface) 功能,自動處理呼叫慣例、型別轉換與記憶體管理。
require("alien")
-- 1. 載入 DLL
local libc = alien.load("msvcrt.dll")
-- 2. 宣告函數簽名:回傳型別, 參數型別...
libc.puts:types("void", "string")
-- 3. 呼叫
libc.puts("test") -- 輸出到 stdout
| Lua 型別 | C 型別 | alien 字串 |
|---|---|---|
| number | int, long, float, double | "int", "long", "float", "double" |
| string | const char* | "string" |
| userdata | void* | "pointer" |
| nil | NULL | - |
使用 ref type 指示 alien 在堆疊分配空間:
local scanf = libc.scanf
scanf:types("int", "string", "ref int", "ref double")
local _, x, y = scanf("%i %lf", 1, 1) -- 後兩參數為佔位
-- 輸入: 23 24.5
-- x=23, y=24.5
const char*,生命週期至呼叫結束。alien.buffer 或 alien.array 分配緩衝區。alien 是 Lua 5.1 純 Lua 環境呼叫系統 DLL 的輕量選擇。