skip to Main Content

What I want to avoid is to capture/ignore the exception when FFI calls a non-existent method.

For example, the following code calls the non_existent_method. However, pcall cannot handle the error.

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

I got the following error with OpenResty/lua-nginx-module.

lua entry thread aborted: runtime error: dlsym(RTLD_DEFAULT, awd): symbol not found

2

Answers


  1. Chosen as BEST ANSWER

    One possible solution would be wrapping the C.non_existent_method call with a lua function.

    For example

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

  2. One more apporach would be to call the index metamethod directly:
    You might want to wrap that into a function:

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

    example:

    
    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
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search