ffi.cdef() for module writers

  • From: Brian Maher <brian@xxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 12 Oct 2012 15:44:26 -0700

Hello LuaJIT Fans,

I've been playing around with the lua jit FFI to bind all sorts of C
libraries and at last I think I've ran into a major stumbling block
for module writers that want their modules to play nicely with other
modules.

Specifically, let's say that I write an FFI to bind to time() POSIX
function which returns a time_t.  So, in my cdef I define the time_t
typedef.

Now let's say that I write another FFI binding that binds to library X
that takes a time_t type and this binding has no knowledge of the
aforementioned POSIX time() binding and therefore this binding also
defines (the same) time_t typedef as above.

If you now write a program that leverages both of these FFI bindings
you run into duplicate definition errors.

The only way I can think of to "fix" this problem is to start a
convention of defining each C symbol in a separate *.lua file.  So, in
the above case the POSIX time() binding build define cdef/time_t.lua
as such:

require("ffi").cdef("typedef long int time_t")

That binding would also define cdef/time.lua as such:

-- Require cdef.time_t so that we can use it in the definition of time():
require("cdef.time_t")
require("ffi").cdef("time_t time()")

The library X binding would also have the exact same cdef.time_t
"module" implementation but depending on LUA_PATH either  the X
binding or the POSIX time() binding's implementation of cdef.time_t
would get loaded.

Unfortunately, this method gets rather tedious... today I simply run
`gcc -E cdef.h` to generate the c definitions for my lua modules (and
perhaps grep out the bits I care about).  So, it seems that I should
write a tool to parse the C header files and generate the various
cdef/*.lua modules... but I don't see a straight forward way of doing
this without writing a C parser.

Does anyone else have a better idea on how to solve this problem?

Thanks,
-Brian

--
Brian Maher >> Glory to God <<

Other related posts: