mystor / rust-cpp

Embed C++ directly inside your rust code!
Apache License 2.0
795 stars 44 forks source link

Document how exceptions are handled #109

Open ShaddyDC opened 11 months ago

ShaddyDC commented 11 months ago

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.

ogoffart commented 11 months ago

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.

ebegumisa commented 8 months ago

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.

ogoffart commented 8 months ago

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