外部链接 C 库中的异常传播

发布于 2024-10-08 13:02:33 字数 195 浏览 2 评论 0原文

我正在编写一个使用外部第三方 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

2024-10-15 13:02:33

异常是否会正确传播到 foo() 中的处理程序?

我认为异常是否通过外部 C 代码传播是未定义的。更糟糕的是,C 代码没有准备好,无法处理异常。 C代码不需要对突然的、意外的返回免疫,所以它不知道RAII等。

当我曾经遇到过这样的情况时,我在返回C API之前捕获了异常,存储它,然后重新抛出它一旦调用从 C API 返回。

Will the exception be correctly propagated to a handler in foo()?

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.

伴我老 2024-10-15 13:02:33

这是一个繁重的平台实现细节。一般来说,异常管道在某种程度上可能能够通过 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.

故人如初 2024-10-15 13:02:33

阅读(并购买!)Herb Sutter 的 C++ 编码标准

#62:
不允许异常传播
跨模块边界。

Read (and buy!) Herb Sutter's C++ Coding Standards

#62 :
Don't allow exceptions to propagate
across module boundaries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文