从 Lua 调用 C 嵌套函数指针
Calling C nested function pointer from Lua
我有以下包含函数指针的 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)
我有以下包含函数指针的 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)