Can I throw C++ exceptions from legacy C callbacks?

橙三吉。 提交于 2019-12-23 07:39:03

问题


I have C++ code that uses some C libraries. The C libraries take C language callbacks. I wrote a callback in my C++ code and now I somehow need to report error from it (but it returns void). I wonder if I can throw an exception from a C callback that is used from C++ code?

This is very difficult for me to understand.

Thanks, Boda Cydo.


回答1:


Yes, you should be able to do so. However, keep in mind it's entirely likely that the C library was not written to be exception safe, and as a result you might leave some of that library's structures in some inconsistent state. It depends entirely on the specific library and on the specific callback function. If nothing else, that library would probably have to be written with C++ support in mind from the beginning with respect to that callback.




回答2:


Yes, you could throw an exception from your C++ function. However, it can only be caught by C++ code so it won't be handled in the legacy library.



来源:https://stackoverflow.com/questions/3177028/can-i-throw-c-exceptions-from-legacy-c-callbacks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!