Closed Rike-cz closed 1 month ago
Rust does not have exceptions, so perhaps you mean to ask how to handle exceptions when a Rust program calls a non-Rust function, but the Rust FFI omnibus is focused on the other direction of integration: calling functions written in Rust from non-Rust programs.
From which language are you speaking of? The concept of exception and mechanisms to handle them in Rust will differ.
Thank you for your reply. I am newbie in Rust, so I wrote "exceptions" but mean "errors/panics", I am looking for way how to deal with panic in Rust code and how to return this information to VFP (Visual FoxPro, very old stuff) through FFI.
Only way I found is catching all panics with std::panic::catch_unwind()
and return it as return type, but still do not look good. So I am looking for better ideas...
How will you manage in your example with addition of integers, if it changes to division and second attribute will be zero?
Recovering from panics is very unreliable. The unwinding cannot cross FFI boundaries, and even if you try to catch_unwind
from within your Rust, the program should not do much more than discard whatever it was doing.
The recommended course of action is design your Rust code to return recoverable errors. From there, this issue would be a duplicate of #57.
How will you manage in your example with addition of integers, if it changes to division and second attribute will be zero?
When anticipating that possibility, you can use checked_div
instead. Then a scheme is needed to convert an Option<u32>
into something compatible with C. Below is an example of this.
#[no_mangle]
pub extern "C" fn division(a: u32, b: u32, out: *mut u32) -> bool {
if let Some(c) = a.checked_div(b) {
unsafe {
*out = c;
}
true
} else {
false
}
}
extern _Bool division(uint32_t a, uint32_t b, uint32_t* out);
Great idea! Thank you very much!
It would be helpful to have examples how to manage exception handling.