lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I've started using FFI, and while it's great overall, one issue has
been bothering me.  Many of the functions I want to expose to lua live
in my executable itself, and the way FFI deals with those functions
(automatically exposing any exported functions in the executable)
doesn't work too well in practice.

- Many of these functions are only designed to be called by LUA.
Since they aren't referenced anywhere else in my code, they tend to
get stripped out at link-time.  My current workaround is to reference
them in another translation unit, which is annoying.

- The functions are only addressable with the exact same name in the
ffi.C namespace.  This isn't always desirable.  For example, I wanted
to use the built-in htonl, htons and friends.  However, they are
actually defined as macros on my system.  This can be trivially fixed
by writing a wrapper function.  However, I can't name the wrapped
function 'htonl', or else I'll have conflicts with the macro.  So I
named my functions htonl2, etc - which means I have to address them
through FFI as 'htonl2'.  Often, I'd like to be able to tell FFI what
name to refer to them, and which namespace to stick them in.

- My functions don't work at all unless I set -Wl,--export-dynamic in
my makefile - which isn't something I really want to do.

I have a suggestion that would solve all 3 of these problems.

What about adding a function to ffi that is something along the lines
of luaL_register / lua_openlib?

static const struct ffi_reg netFuncs [] = {
    {"htonl",htonl2},
    {"ntohl",ntohl2},
    {NULL, NULL}  /* sentinel */
  };

ffi_register(L, "net", netFuncs);

Then, you could reference htonl through ffi.net.htonl.  If you pass
NULL for the second arg, it could go to ffi.C.

Optionally, you could make the first string, rather than just the
function name, the full function declaration, which would serve the
additional purpose of avoiding a ffi.cdef elsewhere.

And since you're referencing the functions now, they won't get
stripped out during the link phase.