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

  • From: "Santhi, Nandu" <nsanthi@xxxxxxxx>
  • To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
  • Date: Fri, 23 Sep 2016 21:08:34 +0000

Another possible technique that may work:
If it is feasible for you, then try converting the static library to a shared 
library using gcc. The original static library should have been originally 
compiled with fPIC for this to work, I believe.
See 
https://stackoverflow.com/questions/655163/convert-a-static-library-to-a-shared-library
 for example.


-          Nandu

From: <luajit-bounce@xxxxxxxxxxxxx> on behalf of bellasys <bellasys@xxxxxxxxx>
Reply-To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
Date: Friday, September 23, 2016 at 1:46 PM
To: "luajit@xxxxxxxxxxxxx" <luajit@xxxxxxxxxxxxx>
Subject: Re: How to call functions from a static library in Luajit



On Fri, Sep 23, 2016 at 1:47 AM, Mike Pall 
<mikelj-1609@xxxxxxx<mailto: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: