lua - 使用 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
解决方案
另一种方法是直接调用索引元方法:您可能希望将其包装到一个函数中:
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
推荐阅读
- python - pandas填写log数据中没有记录的日期
- sql - SAP DBTech JDBC:[257]:sql 语法错误:“:OT”附近的语法不正确
- laravel-8 - Laravel 8 SQLSTATE [42S02]:找不到基表或视图:1146 表 'dummydb.users' 不存在
- mysql - 如何在 MySQL 中显示一个表中的所有行并从另一个表中计数
- python - python数据框并用不均匀的时间序列绘制
- hibernate - 如何在 JPA 中使用规范进行左连接、分组、计数和 IN 子句?
- keras - 如何将 decode_batch_predictions() 方法添加到 Keras Captcha OCR 模型中?
- java - Spring Boot 说没有可用的名为“entityManagerFactory”的bean
- python-3.x - 使用字典将实体从一个位置移动到另一个位置
- asp.net-core - 为什么我的 Guid 被清除并且时间被从 AspnetCore 应用程序中的 DateTime 字段中剥离?