File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -530,3 +530,37 @@ The `extern` makes this function adhere to the C calling convention, as
530
530
discussed above in "[ Foreign Calling
531
531
Conventions] ( ffi.html#foreign-calling-conventions ) ". The ` no_mangle `
532
532
attribute turns off Rust's name mangling, so that it is easier to link to.
533
+
534
+ # FFI and panics
535
+
536
+ It’s important to be mindful of ` panic! ` s when working with FFI. This code,
537
+ when called from C, will ` abort ` :
538
+
539
+ ``` rust
540
+ #[no_mangle]
541
+ pub extern fn oh_no () -> ! {
542
+ panic! (" Oops!" );
543
+ }
544
+ # fn main () {}
545
+ ```
546
+
547
+ If you’re writing code that may panic, you should run it in another thread,
548
+ so that the panic doesn’t bubble up to C:
549
+
550
+ ``` rust
551
+ use std :: thread;
552
+
553
+ #[no_mangle]
554
+ pub extern fn oh_no () -> i32 {
555
+ let h = thread :: spawn (|| {
556
+ panic! (" Oops!" );
557
+ });
558
+
559
+ match h . join () {
560
+ Ok (_ ) => 1 ,
561
+ Err (_ ) => 0 ,
562
+ }
563
+ }
564
+ # fn main () {}
565
+ ```
566
+
You can’t perform that action at this time.
0 commit comments