Search code examples
cdllluaffiluajit

Creating a struct of callbacks in LuaJIT FFI


So first I load in a DLL I need

local ffi = require("ffi")
local theDLL = ffi.load("thisDLL")

in the ffi cdef I have this struct

ffi.cdef [[
    typedef struct {
        /*
        * begin_proj callback
        */
        bool (__cdecl *begin_proj)(char *proj);

        /*
        * save_proj_state
        */
        bool (__cdecl *save_proj_state)(unsigned char **buffer, int *len);
    } StructCallbacks;

I also have this function in the cdef

__declspec(dllexport) int __cdecl start_session(StructCallbacks *cb);

Now I would like to call this function

print(theDLL.start_session(myCallbacks))

the question is how can I pass the structs the function needs (how do I make myCallbacks a struct of callbacks to Lua functions)?


Solution

  • Just create the struct and assign the fields to Lua functions, as you would with any other value.

    local callbacks = ffi.new("StructCallbacks")
    
    callbacks.begin_proj = function(proj) return false end
    callbacks.save_proj_state = function(buffer, len) return true end
    

    See the FFI callback docs for more in-depth information on callbacks.