从 Lua 调用 C 嵌套函数指针

标签 c pointers lua ffi

我有以下包含函数指针的 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/

相关文章:

c++ - 如何将函数作为参数传递给参数?

c - 显式算术,编译器会处理它吗?

c++ - 使用 void *pointer to object 的安全性

c++ - 为什么这个指向常量指针的指针赋值是非法的?

string - 提取字符串中的信息

c - 即使在我使用 malloc() 分配内存后,free() 也无法正常工作

c - 我正在寻找一个能够计算 4x4 和 3x3 矩阵数学的 C 库

c++ - 在 C++ 中使用创建的类动态分配数组时遇到问题

c++ - 如何使可插拔工厂与lua一起工作?

lua - 为什么 Lua 5.3 找不到包含的路径(缺少 : LUA_INCLUDE_DIR)