LuaJIT 使用 FFI 调用不存在的方法时出现错误处理

我想要避免的是当 FFI 调用不存在的方法时捕获或忽略异常。

例如,下面的代码调用了 non_existent_method 方法。但是,pcall 无法处理这个错误。

local ffi = require "ffi"
local C = ffi.C

ffi.cdef [[
    int non_existent_method(int num);
]]

local ok, ret = pcall(C.non_existent_method, 1)

if not ok then
    return
end

我在 OpenResty/lua-nginx-module 中得到了以下错误。

lua entry thread aborted: runtime error: dlsym(RTLD_DEFAULT, awd): symbol not found
点赞
用户4658633
用户4658633

一种可能的解决方案是用 Lua 函数包装 C.non_existent_method 调用。

例如


local ok, ret = pcall(function()
    return C.non_existent_method(len)
end)

if not ok then
    ......
end
2021-08-23 08:33:09
用户5688146
用户5688146

另一个方法是直接调用索引元方法:

你可能想把它包装成一个函数:

local ffi_mt = getmetatable(ffi.C)
function is_valid_ffi_call(sym)
  return pcall(ffi_mt.__index, ffi.C, sym)
end

例如:

ffi.cdef[[void (*foo)();]]
ffi.cdef[[int puts(const char *);]]

a,func = is_valid_ffi_call("foo")
-- false, "error message: symbol not found or missing declaration, whatever it is"

a,func = is_valid_ffi_call("puts")
-- true, cdata<int ()>: 0x7ff93ad307f0
2021-08-24 09:22:16