guile-user
[Top][All Lists]
Advanced

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

Re: C++ Foreign Function Interface


From: Chris Vine
Subject: Re: C++ Foreign Function Interface
Date: Mon, 14 Mar 2016 19:22:16 +0000

On Mon, 14 Mar 2016 21:34:24 +0530
Arun Isaac <address@hidden> wrote:
> Hans Åberg <address@hidden> writes:
> 
> > When calling C++ from C, you can’t pass a C++ exception through the
> > C code. So in my example code, there are conversions between C++ and
> > Guile exceptions.  
> 
> Yeah, this was the discussion in the other thread you linked
> to. Unfortunately, I don't know anything about C++ exceptions, and
> hence didn't understand what your code was doing. Can any of this be
> integrated into guile itself, so that C++ FFI will be easier for the
> end programmer?

I am not a guile developer but I doubt (as a C++ programmer) that that
is worth the effort.  If you are calling into a C++ library from any C
code then you need to consider what exceptions the library might
throw.  Your 'extern "C"' interface then needs to catch these
exceptions and turn them into something else.  That might mean
providing a return value indicating an error condition, or if you are
programming in guile mode with libguile at that point might mean
throwing a guile exception.  You can probably ignore std::bad_alloc.
On most modern systems that exception will not be thrown (you will just
thrash), and when you are out of memory there is nothing you can do to
recover anyway as the kernel will take over.  The overall point is that
you need to ensure that, if you are in guile mode, any C++ exceptions
are handled locally and do not escape out of a guile dynamic extent nor
out of a function with C calling convention.

You also need to be aware of the converse, namely that if you throw a
guile exception out of C++ code, there are no C++ objects with
non-trivial destructors in scope when the guile exception is thrown, or
you will get undefined behaviour: most probably the destructors of the
C++ objects will not be called.  A guile exception is basically a long
jump up the stack.  But that is almost certainly not an issue if all
you are doing is calling into a C++ library when in guile mode.  It
will be an issue if you are yourself constructing your own C++ objects
when in guile mode.

In most cases this is pretty easy to accomplish once you get the hang
of it.

Chris




reply via email to

[Prev in Thread] Current Thread [Next in Thread]