<分区>
我正在使用 C++ 中的 C/Fortran 库,该库调用 exit()。我希望它抛出一个异常,以便调用我的 C++ 程序中的析构函数。我已经能够创建一个抛出异常的 exit 定义,但仍然会调用 terminate。是否可以防止调用终止并允许发生正常的异常处理?
更新:在评论中指出这在 x64 上有效但在 x86 上失败,所以主要问题是“有没有办法让 x86 像 x64 一样工作?”。
更新 2:请参阅我关于为什么这在 x86 上不起作用以及如何修复它的回复。
这是我的测试代码:
测试异常.c
#include <stdlib.h>
void call_c() { exit(1); }
测试异常.cpp
#include <iostream>
#include <stdexcept>
extern "C" void call_c();
extern "C" void exit(int value)
{
throw std::runtime_error(std::string("Throwing an exception: ") + char('0' + value));
}
int main()
{
try {
call_c();
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
使用以下命令构建:
gcc -c test_exception.c -o test_exception_c.o
g++ -c test_exception.cpp -o test_exception_cpp.o
g++ test_exception_c.o test_exception_cpp.o -o test_exception