1

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?

7
  • 1
    void (*db_test)(void); wrong prototype, should be void (*db_test)(struct db *); Commented May 4, 2016 at 8:29
  • no, it's not wrong. db_test is different function pointer, it does not have any args. It's not relevant to the question anyway Commented May 4, 2016 at 8:31
  • Ah, then why are you showing this one? Commented May 4, 2016 at 8:35
  • Just to show that I can easily call free function pointers, but not the nested one (that belongs to struct) Commented May 4, 2016 at 8:36
  • Are you assigning some function to test before calling it? db.test = somefunction Commented May 4, 2016 at 8:40

1 Answer 1

2
+50

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.