Export host C functions to luajit FFI without export

  • From: Domingo Alvarez Duarte <mingodad@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Tue, 20 Jan 2015 21:44:23 -0800

After some thought I found a solution that is clean and sugest it to be
added to luajit.

On the header "lj_clib.h"

typedef void *(*clib_getsym_func_ptr)(CLibrary *cl, const char *name);
LUA_API clib_getsym_func_ptr set_lj_clib_get_sym(clib_getsym_func_ptr
funcPtr);

On the "lj_clib.c" just after the following comment line:

/* -- C library indexing --------------------------------------------------
*/

static clib_getsym_func_ptr clib_getsym_funcPtr = clib_getsym;

clib_getsym_func_ptr set_lj_clib_get_sym(clib_getsym_func_ptr funcPtr)
{
    clib_getsym_func_ptr oldPtr = clib_getsym_funcPtr;
    clib_getsym_funcPtr = funcPtr;
    return oldPtr;
}

/* Index a C library by name. */
TValue *lj_clib_index(lua_State *L, CLibrary *cl, GCstr *name)
{
...
      //void *p = clib_getsym(cl, sym); //// change this line by the
following
      void *p = (*clib_getsym_funcPtr)(cl, sym);
...
}


On the lua host file:
//if we have this definition on "luajit.h" we do not need to add it here
manually

typedef void *(*clib_getsym_func_ptr)(void *cl, const char *name);
extern clib_getsym_func_ptr set_lj_clib_get_sym(clib_getsym_func_ptr
funcPtr);

static clib_getsym_func_ptr old_clib_getsym_func_ptr;

void *my_clib_getsym_func(void *cl, const char *name)
{
    void *funcPtr= NULL ;
    printf("my_clib_getsym_func => %s\n", name);
    if(strcmp(name, "myprintf") == 0)
    {
        funcPtr = printf;
    }
    else
    {
        funcPtr = (*old_clib_getsym_func_ptr)(cl, name);
    }
    return funcPtr;
}

Before using luajit:

old_clib_getsym_func_ptr = set_lj_clib_get_sym(my_clib_getsym_func);


That's it a clean way to expose host functions to luajit without make then
external linkable.

Again I hope this will be useful to other people also and propose to add to
luajit !

Cheers !

Other related posts: