跨C API边界传递异常 [英] Passing exceptions across a C API boundary

查看:316
本文介绍了跨C API边界传递异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a library in C++ which uses an older C API. The client of my library can specify callback functions, which are indirectly called through my library which is called through the C API. This means that all exceptions in the client callbacks must be handled.

我的问题是:我如何在边界的一侧捕获异常并重新抛出一旦C API边界已被重新循环,并且执行返回到C ++版本中,以便异常可以由客户端代码处理。

My question is this: how can I catch the exception on one side of the boundary and re-throw it once the C API boundary has been recrossed and the execution is back in C++ land so that the exception can be handled by client code?

推荐答案

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

With C++11 we could use:

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);

在C ++ 11之前,仍然可以通过 Boost异常

Before C++11 these can still be used via Boost Exception.

这篇关于跨C API边界传递异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆