外部链接 C 库中的异常传播
我正在编写一个使用外部第三方 C 库的 C++ 库。因此,我的库将调用该第三方库中的函数,而第三方库将回调到我库的不同部分。
我想知道在这种情况下异常会发生什么? 假设 MyLib::foo() 调用外部 C 库函数,最终调用 MyLib::bar(),并且 bar 抛出异常,会发生什么?异常会正确传播到 foo() 中的处理程序吗?
谢谢!
I am writing a C++ library that uses an external third party C library. So my library will call functions in this third party library and the third party library will call back into a different part of my library.
I am wondering what happens to exceptions in this case?
Say MyLib::foo() calls external C library function which eventually calls MyLib::bar(), and bar throws an exception, what happens? Will the exception be correctly propagated to a handler in foo() ?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为异常是否通过外部 C 代码传播是未定义的。更糟糕的是,C 代码没有准备好,无法处理异常。 C代码不需要对突然的、意外的返回免疫,所以它不知道RAII等。
当我曾经遇到过这样的情况时,我在返回C API之前捕获了异常,存储它,然后重新抛出它一旦调用从 C API 返回。
I think whether exceptions propagate through external C code is undefined. What's even worse, the C code is unprepared and unable to handle the exception. C code doesn't need to immune against sudden, unexpected returns, so it knows no RAII etc.
When I was once faced with such a situation, I caught the exception before returning to the C API, stored it, and re-threw it once the call came back from the C API.
这是一个繁重的平台实现细节。一般来说,异常管道在某种程度上可能能够通过 C 函数激活帧展开堆栈。这是必要的,因为 CRT 通常是用 C 编写的。但是,C 代码不太可能对此感到满意,状态发生了变化且无法恢复。
万一这是 Windows,C 代码确实可以解决这个问题。 C++ 异常依赖于 Windows 内置的通用异常支持,称为结构化异常处理 (SEH)。您可以使用 __try 和 __ except 关键字来调用可以恢复 C 代码状态的异常过滤器。显然这不是便携式的。
请不要在未提及实施细节的情况下询问实施细节问题。
It is a heavy platform implementation detail. In general, the exception plumbing is somewhat likely to be able to unwind the stack through C function activation frames. Necessary because the CRT is often written in C. However, the C code is pretty unlikely to be happy about it, state got mutated that cannot be restored.
Just in case this is Windows, the C code does have a shot at it. C++ exceptions are piggy-backed onto the generic exception support built into Windows, called Structured Exception Handling (SEH). You use the __try and __except keywords to call an exception filter that can restore the C code state. Obviously this is not portable.
Never ask an implementation detail question without mentioning the implementation details, please.
阅读(并购买!)Herb Sutter 的 C++ 编码标准
Read (and buy!) Herb Sutter's C++ Coding Standards