Re: ffi.cdef()

  • From: demetri <demetri.spanos@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 20 Jul 2012 01:55:58 -0700

>
> How and when does ffi.cdef() execute ?
>
Does luajit translate and register these definitions during the first file
> load or does it execute as it is located in the file ?
>

ffi.cdef executes just like any other Lua function. You can verify this for
yourself with the following.

ffi = require "ffi"
function foo () ffi.cdef[[ typedef int myInt; ]] end
-- this will fail because myInt hasn't been declared yet
a = ffi.new("myInt[10]")
-- this would work though
foo()
b = ffi.new("myInt[10]")

I've been toying with the idea of having local ffi.cdef() definitions per
> lua functions - in order to hide the C functions from "global" ffi.C scope.
>

I'm not 100% sure I understand your question, but as you can see from the
example above the cdef call loads the symbol into the ffi.C namespace
regardless of the invoking function's scope/environment (analogously, if
you load a dynamic library it loads into that library's namespace).  So,
hiding cdefs inside function calls doesn't accomplish anything aside from
localizing the declarations and controlling when they execute (which can be
good for code clarity, and can enable some tricks with dynamically
generated C bindings, but doesn't provide any namespace structure).

Could this be considered as a good idea or would it just add unnecessary
> overhead to lua functions ?


Depending on your coding style, it could potentially be a win for clarity.
If you're repeatedly calling a function with a cdef declaration (which is
presumably redundant after the first invocation unless you're doing some
dynamic cdef trickery) then presumably there's some small overhead in the
cdef function call and the check against pre-existing symbols.

Demetri

Other related posts: