我有以下包含函数指针的 C 结构:
struct db {
struct db_impl *impl;
void (*test)(struct db *self); // How to invoke it from Lua??
};
void (*db_test)(void); // this I can invoke from Lua
struct db * get_db() {
// create and init db
struct db * db = init ...
db->test = &db_real_impl; // db_real_impl is some C function
return db;
}
所以初始化后的测试函数指针指向某个函数。
现在我需要使用 FFI 库从 Lua 调用该函数,但它失败并出现错误:'void' is not callable
。
local db = ffi.C.get_db()
db.test(db) -- fails to invoke
-- Error message: 'void' is not callable
ffi.C.db_test() -- this works fine
在 C 中,代码将是:
struct db *db = get_db();
db->test(db);
在 Lua 中,我可以很容易地调用自由函数指针,但不能从结构中调用函数指针。如何从 Lua 中调用它?
最佳答案
一个解决方案似乎被指出: http://lua-users.org/lists/lua-l/2015-07/msg00172.html
ffi.cdef[[
typedef void (*test)(struct db *);
]]
local db = get_db()
local call = ffi.cast("test", db.test)
call(db)
关于从 Lua 调用 C 嵌套函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37022341/