exception propagation in externally linked C libra

2019-06-25 05:08发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

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

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