Search code examples
cpointersluaffi

Calling C nested function pointer from Lua


I have the following C struct, that contains function pointer:

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;
}

So the test function pointer after initialization points to some function. Now I need to call that function from Lua using FFI library, but it fails with error: '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

In C the code would be:

struct db *db = get_db();
db->test(db);

In Lua I'm able to invoke free function pointers easily, but can't invoke function pointer from struct. How to invoke it from Lua?


Solution

  • A solution seems to be pointed out in : 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)