我正在测试Rust库,这些库可能会崩溃,并在C++代码中使用它们.我有以下图书馆:
Cargo.toml
:
[package]
name = "boom"
version = "0.1.0"
edition = "2018"
[dependencies]
libc = "0.2"
[lib]
crate-type=["staticlib"]
src/lib.rs
:
#[no_mangle]
pub extern "C" fn boom() {
panic!("Oh no, something went wrong!");
}
我正在使用cargo build
构建它,并使用以下C++代码(boom.cpp
文件)中的结果:
// g++ -g boom.cpp -L./target/debug -lboom -o boom
extern "C" {
void boom();
}
int main() {
boom();
}
结果是:
thread '<unnamed>' panicked at src/lib.rs:3:5:
Oh no, something went wrong!
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fatal runtime error: failed to initiate panic, error 5
到目前为止一切顺利.
我试图将这种panic 捕捉到我的C++代码中.我try 了以下操作:
// g++ -g boom.cpp -L./target/debug -lboom -o boom
#include <stdexcept>
extern "C" {
void boom();
}
int main() {
try
{
boom();
}
catch(const std::exception& e)
{
printf("exception captured\n");
}
}
但结果是相同的,而不是预期的exception captured
消息.
C++代码中是否有任何方法可以捕捉Rust库产生的panic ?或者,反过来说,有没有办法将Rustpanic 转化为C++可捕获的异常?