7.2.8 C++ 错误处理
08-C++ 错误处理 — Comprehensive Rust
1分钟内可阅读完
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/android/interoperability/cpp/cpp-exception.html
7.2.8 C++ 错误处理
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
include!("example/include/example.h");
fn fallible(depth: usize) -> Result<String>;
}
}
fn main() {
if let Err(err) = ffi::fallible(99) {
eprintln!("Error: {}", err);
process::exit(1);
}
}
- 声明为返回
Result的 C++ 函数会在 C++ 一侧捕获任何抛出的异常,并将其作为Err值返回给调用的 Rust 函数。- 若异常从 CXX 桥接未声明返回
Result的 extern “C++” 函数抛出,程序会调用 C++ 的std::terminate。行为等价于同一异常穿过一个noexceptC++ 函数。