Re: Export host C functions to luajit FFI without export

  • From: Hendrik Polczynski <hendrikpolczyn@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 21 Jan 2015 12:46:59 +0100

Hi,

this is a good idea to implement this as callback, I previously thought
about implementing it directly into LuaJIT with lookup maps
and functions to register functions and modules, but this solution is much
more flexible.

It is also a required solution if the Module APIs fail or are not available
as on certain embedded/realtime OSes.

Thanks!

2015-01-21 6:44 GMT+01:00 Domingo Alvarez Duarte <mingodad@xxxxxxxxx>:

> 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: