我正在使用C++的C/Fortran库,并且库调用exit().我希望它抛出异常,以便调用我的C++程序中的析构函数.我已经能够创建一个抛出异常的exit定义,但是仍然会调用terminate.是否有防止终止被调用并允许正常的异常处理发生?
更新:在评论中指出,这适用于x64但在x86上失败,因此主要问题是"有没有办法使x86像x64一样工作?".
更新2:请参阅我的回答,了解为什么这不适用于x86以及如何解决它.
这是我的测试代码:
test_exception.c
#include <stdlib.h>
void call_c() { exit(1); }
Run Code Online (Sandbox Code Playgroud)
test_exception.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;
}
Run Code Online (Sandbox Code Playgroud)
使用以下命令构建:
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
Run Code Online (Sandbox Code Playgroud)