Re: Using exceptions with FFI

  • From: Mike Pall <mike-1208@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 17 Aug 2012 21:29:45 +0200

Simon Cooke wrote:
> I'm using the FFI library to call C++ code that may throw exceptions -

That's not entirely safe and it'll happily crash on some
platforms, if/when the FFI call is JIT-compiled.

> My initial solution creates a Lua callback function that takes the
> error message as its argument and calls error(ffi.string(message)).

See: http://luajit.org/ext_ffi_semantics.html#callback

  "It's allowed to throw errors across a callback invocation,
  but it's not advisable in general. Do this only if you know
  the C function, that called the callback, copes with the
  forced stack unwinding and doesn't leak resources."

> I wondered if there might be a better solution, or if something
> equivalent to the existing "C call wrapper" feature might be a
> possibility.

Well .. one would need to communicate back the error condition
from the FFI call (and then exit the trace). Alas, there's no
provision for this, other than ABI-compliant exception handling.

> Would native support for intercepting throw "..." be
> feasible, for example?

The main difficulties are that a) unwinding across JIT-compiled
code is not entirely safe, since it assumes 'nothrow' semantics
for FFI C calls and b) one would need to somehow inject the unwind
info for the dynamically generated machine code on x64 platforms.
Windows/x64 has a documented, but clumsy API for that, but AFAIK
on POSIX/x64, you're SOL.

The do-it-yourself solution would be to add a try/catch wrapper on
the C++ side, return some error code and then check for it on the
Lua side and call error() on failure.

--Mike

Other related posts: