|
15 | 15 | pub mod cast; |
16 | 16 | pub mod module; |
17 | 17 |
|
18 | | -use cxx::{type_id, CxxString, CxxVector, ExternType, SharedPtr, UniquePtr}; |
| 18 | +use cxx::{ |
| 19 | + type_id, CxxException, CxxString, CxxVector, ExternType, SharedPtr, ToCxxException, UniquePtr, |
| 20 | +}; |
19 | 21 | use std::fmt::{self, Display}; |
20 | 22 | use std::mem::MaybeUninit; |
21 | 23 | use std::os::raw::c_char; |
22 | 24 |
|
| 25 | +/// A custom error with special exception handling. |
| 26 | +pub struct CustomError { |
| 27 | + pub data: i32, |
| 28 | +} |
| 29 | + |
| 30 | +impl CustomError { |
| 31 | + pub fn get_data(&self) -> i32 { |
| 32 | + self.data |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +impl ToCxxException for CustomError { |
| 37 | + fn to_cxx_exception(&self) -> CxxException { |
| 38 | + ffi::make_custom_exception(self) |
| 39 | + } |
| 40 | +} |
| 41 | + |
23 | 42 | #[cxx::bridge(namespace = "tests")] |
24 | 43 | pub mod ffi { |
25 | 44 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] |
@@ -218,6 +237,21 @@ pub mod ffi { |
218 | 237 | fn ns_c_take_ns_shared(shared: AShared); |
219 | 238 | } |
220 | 239 |
|
| 240 | + extern "Rust" { |
| 241 | + type CustomError; |
| 242 | + fn get_data(&self) -> i32; |
| 243 | + } |
| 244 | + |
| 245 | + unsafe extern "C++" { |
| 246 | + include!("tests/ffi/tests.h"); |
| 247 | + |
| 248 | + fn make_custom_exception(error: &CustomError) -> CxxException; |
| 249 | + fn catch_custom_exception() -> Result<()>; |
| 250 | + |
| 251 | + fn forward_exception_inner() -> Result<()>; |
| 252 | + fn forward_exception_outer() -> Result<()>; |
| 253 | + } |
| 254 | + |
221 | 255 | extern "C++" { |
222 | 256 | include!("tests/ffi/module.rs.h"); |
223 | 257 |
|
@@ -312,6 +346,9 @@ pub mod ffi { |
312 | 346 |
|
313 | 347 | #[cxx_name = "rAliasedFunction"] |
314 | 348 | fn r_aliased_function(x: i32) -> String; |
| 349 | + |
| 350 | + fn throw_custom_exception() -> Result<()>; |
| 351 | + fn forward_exception_middle() -> Result<()>; |
315 | 352 | } |
316 | 353 |
|
317 | 354 | struct Dag0 { |
@@ -646,3 +683,14 @@ fn r_try_return_mutsliceu8(slice: &mut [u8]) -> Result<&mut [u8], Error> { |
646 | 683 | fn r_aliased_function(x: i32) -> String { |
647 | 684 | x.to_string() |
648 | 685 | } |
| 686 | + |
| 687 | +fn throw_custom_exception() -> Result<(), CustomError> { |
| 688 | + Err(CustomError { data: 4711 }) |
| 689 | +} |
| 690 | + |
| 691 | +fn forward_exception_middle() -> Result<(), CxxException> { |
| 692 | + ffi::forward_exception_inner().map_err(|e| { |
| 693 | + assert_eq!(e.what(), "forward test exc"); |
| 694 | + e.into() |
| 695 | + }) |
| 696 | +} |
0 commit comments