rust-cpp icon indicating copy to clipboard operation
rust-cpp copied to clipboard

Document how exceptions are handled

Open ShaddyDC opened this issue 2 years ago • 3 comments

I'm evaluating different options to use C++ code from rust, and an important point for me is that error handling should be seamless. It would be convenient if what happens when an exception crosses the boundary was documented somewhere. The only relevant information I found was #21.

If anybody else wonders as well, I've now tried it myself, and it results in this crash:

let result = unsafe {
    cpp!([] -> i32 as "std::int32_t" {
            throw std::runtime_error("oops");
            return 0;
        })
    };

fatal runtime error: Rust cannot catch foreign exceptions
Aborted (core dumped)

In hindsight, this is the obvious behaviour, but it's still useful to have it explicitly mentioned.

ShaddyDC avatar Aug 29 '23 15:08 ShaddyDC

Right, as of now, nothing had been done to handle exceptions as they cross boundaries.

Since Rust 1.71, we could use extern "C-unwind" But that would not result in the same behaviour as the rust runtime wouldn't know how to catch it.

ogoffart avatar Aug 29 '23 17:08 ogoffart

Right, as of now, nothing had been done to handle exceptions as they cross boundaries.

Since Rust 1.71, we could use extern "C-unwind" But that would not result in the same behaviour as the rust runtime wouldn't know how to catch it.

True, though I think C++ would be able to catch it somewhere else in the callstack, which would be useful.

Perhaps this library should switch to generating extern "C-unwind" regardless (or maybe provide a configuration option which allows for choosing between extern "C-unwind" and extern "C" but still defaulting to extern "C-unwind").

Unless I've misunderstood RFC-2945, using extern "C-unwind" would bring two benefits:

  1. Make it clear what happens when rust calls C++ which calls rust which calls C++, etc, and somewhere there's a C++ exception or a rust panic. For instance, when using rust-cpp with callbacks or when using the nifty rust! macro.

  2. Probably more importantly, avoiding the undefined behaviour columns in this table, which as I understand it, is currently a hazard that rust-cpp users have had to accept.

I'm happy to write such a PR if this is something the maintainers think is worthwhile and not something I'm mistaken about.

ebegumisa avatar Nov 29 '23 01:11 ebegumisa

@ebegumisa your comment seems sensible. a PR would be welcome.

ogoffart avatar Nov 29 '23 08:11 ogoffart