Re: How to call functions from a static library in Luajit

  • From: bellasys <bellasys@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 23 Sep 2016 12:46:53 -0700

On Fri, Sep 23, 2016 at 1:47 AM, Mike Pall <mikelj-1609@xxxxxxx> wrote:

Fu, Qiaobin wrote:
I am a newer for Lua and LuaJIT. Currently, I have a need in a
situation that C host program calls Lua scripts, and the Lua
scripts calls C functions from C modules via Luajit FFI. As far
as I know, the FFI library only allows us to load shared
libraries. However, if I want to call C functions in a static
library, is there any way to achieve this via LuaJIT?

First, create a struct with function pointers:

  struct myfuncs {
    int (*some_function_name)(int a, int b);
    void *(*another_function_name)(char *x, const char *y);
    ...
  };

Then make a static struct on the C side and fill it with the
function pointers. Make a lightuserdata object from the struct
pointer with lua_pushlightuserdata(). Pass that Lua object to
LuaJIT, e.g. as an argument of lua_call/lua_pcall or via a global.

On the LuaJIT side, declare the identical struct with ffi.cdef.
Then cast that lightuserdata argument back to the struct pointer:

  -- Assumes the lightuserdata is in the variable ud.
  myfuncs = ffi.cast("struct myfuncs *", ud)

All of the above should only be done once at initialization.

Now, whenever you want to call one of these functions via the FFI,
simply reference them from the struct. E.g.:

  -- That's really an FFI call.
  local y = myfuncs.some_function_name(1, 2)

--Mike



@Mike

thanks very much! This brings the pieces together, I see the lightuserdata
object is useful in either case.


-- 

Be Miraculous!

~Max

Other related posts: