mystor / rust-cpp

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

Add an option for automatically handling exceptions #21

Open mystor opened 6 years ago

mystor commented 6 years ago

If the C++ code captured throws an exception, it might be nice to have an option for rust-cpp to add an exception handler which translates the exception into a rust panic.

This would have overhead so we may not want it to be the default.

usamec commented 6 years ago

I would really love this feature. So instead of this:

    unsafe {
            let mut error_p: *mut i8 = ptr::null_mut();
            cpp!([..., mut error_p as "char*"] {
                try {
                    foo();
                } catch (std::exception& e) {
                    auto what = e.what();
                    error_p = new char[strlen(what)+1];
                    strcpy(error_p, what);
                }
            });
            if !error_p.is_null() {
                let msg = CStr::from_ptr(error_p).to_str().unwrap();
                panic!("{}", msg);
            }
        };

I would get something much simpler.

ratijas commented 3 years ago

+1 for this feature. Exceptions are not FFI-safe, and should be handled at boundaries. However, some code is guaranteed to be exception-free, e.g. using noexcept C++ attribute.

In spirit of Rust, exception handling wrapper should be opt-out (on be default) instead of opt-in, which brings us to a question of choosing an appropriate syntax for the macro — or add new macro, like cpp_try! or something. Not sure is it would make sense to wrap C++ exceptions in Rust's Result rather than continue unwinding via panic!, but I think that's debatable.

ahmed-masud commented 2 years ago

In spirit of Rust, exception handling wrapper should be opt-out (on be default) instead of opt-in, which brings us to a question of choosing an appropriate syntax for the macro — or add new macro, like cpp_try! or something. Not sure is it would make sense to wrap C++ exceptions in Rust's Result rather than continue unwinding via panic!, but I think that's debatable.

IMHO A Result is more inline than a panic! because a lot of this would be used to write libraries and libraries should not panic!