rust-cpp
rust-cpp copied to clipboard
Add an option for automatically handling exceptions
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.
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.
+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.
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 viapanic!, 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!