【问题标题】:luaJIT error handling with FFI calls a non-existent method使用 FFI 的 luaJIT 错误处理调用不存在的方法
【发布时间】:2021-10-23 14:33:03
【问题描述】:

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

【问题讨论】:

  • 当您使用键 non_existent_method 索引 C 时会发生错误。

标签: lua ffi luajit


【解决方案1】:

另一种方法是直接调用索引元方法: 你可能想把它包装成一个函数:


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


【讨论】:

    【解决方案2】:

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

    例如

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

    【讨论】:

      猜你喜欢
      • 2018-01-21
      • 2015-10-13
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 2019-11-06
      相关资源
      最近更新 更多