跨C API边界传递异常

Set*_*gie 9 c++ exception-handling exception c-api

我正在用C++编写一个使用旧版C API的库.我的库的客户端可以指定回调函数,它通过我的库间接调用,通过C API调用.这意味着必须处理客户端回调中的所有异常.

我的问题是:如何在边界的一侧捕获异常,并在C API边界重新生成后重新抛出它,并且执行返回到C++域,以便客户端代码可以处理异常?

ken*_*ytm 5

使用C++ 11,我们可以使用:

std::exception_ptr active_exception;

try
{
    // call code which may throw exceptions
}
catch (...)
{
    // an exception is thrown. save it for future re-throwing.
    active_exception = std::current_exception();
}

// call C code
...

// back to C++, re-throw the exception if needed.
if (active_exception)
    std::rethrow_exception(active_exception);
Run Code Online (Sandbox Code Playgroud)

在C++ 11之前,这些仍然可以通过Boost Exception使用.