Skip to content

Commit ef45ec0

Browse files
authoredDec 7, 2016
Rollup merge of #38225 - Cobrand:patch-1, r=GuillaumeGomez
Update book/ffi to use catch_unwind r? @GuillaumeGomez The doc mentioned to spawn a new thread instead of using catch_unwind, which has been the recommended way to catch panics for foreign function interfaces for a few releases now. This commit fixes that.
2 parents 4fb89b1 + 614b74c commit ef45ec0

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed
 

‎src/doc/book/ffi.md

+14-9
Original file line numberDiff line numberDiff line change
@@ -662,26 +662,31 @@ attribute turns off Rust's name mangling, so that it is easier to link to.
662662

663663
It’s important to be mindful of `panic!`s when working with FFI. A `panic!`
664664
across an FFI boundary is undefined behavior. If you’re writing code that may
665-
panic, you should run it in another thread, so that the panic doesn’t bubble up
666-
to C:
665+
panic, you should run it in a closure with [`catch_unwind()`]:
667666

668667
```rust
669-
use std::thread;
668+
use std::panic::catch_unwind;
670669

671670
#[no_mangle]
672671
pub extern fn oh_no() -> i32 {
673-
let h = thread::spawn(|| {
672+
let result = catch_unwind(|| {
674673
panic!("Oops!");
675674
});
676-
677-
match h.join() {
678-
Ok(_) => 1,
679-
Err(_) => 0,
675+
match result {
676+
Ok(_) => 0,
677+
Err(_) => 1,
680678
}
681679
}
682-
# fn main() {}
680+
681+
fn main() {}
683682
```
684683

684+
Please note that [`catch_unwind()`] will only catch unwinding panics, not
685+
those who abort the process. See the documentation of [`catch_unwind()`]
686+
for more information.
687+
688+
[`catch_unwind()`]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
689+
685690
# Representing opaque structs
686691

687692
Sometimes, a C library wants to provide a pointer to something, but not let you

0 commit comments

Comments
 (0)
Please sign in to comment.