首页 > 解决方案 > 使用 FFI 的 luaJIT 错误处理调用不存在的方法

问题描述

我要避免的是在 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

标签: luaffiluajit

解决方案


另一种方法是直接调用索引元方法:您可能希望将其包装到一个函数中:


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



推荐阅读