链接到 C++ 时在 C 中使用 setjmp 和 longjmp;图书馆
我想在链接到用 C++ 实现的库(但具有 C API)的 C 程序中使用 setjmp 和 longjmp。
C++ 代码确实进行动态内存分配,并且指针通过 API 传递,但只要代码的 C 端正确管理这些(不透明)对象,使用 longjmp 时就不应该出现任何混乱,对吧?
我知道在 C++ 代码中使用这些函数不安全,但是在链接到 C++ 代码的 C 代码中应该安全吗?
I would like to use setjmp and longjmp in a C program that links to a library that is implemented in C++ (but has a C API).
The C++ code does do dynamic memory allocation and pointers get passed through the API, but as long as the C side of the code manages those (opaque) objects correctly, there shouldn't be any messing up when using longjmp, right?
I know it's not safe to use these functions in C++ code, but should it be safe in C code that is linked to C++ code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从 C 代码中调用 C++ 函数这一事实并不会使 setjmp 和 longjmp 比以往更加不安全。
重要的是,如果您的库分配资源,您必须有适当的恢复代码,以确保在调用 longjmp 后正确释放这些资源。虽然这对于您自己的分配来说可能很容易,但对于 C++ 库来说可能很困难或不可能,具体取决于您使用的 C 接口的结构。
The fact that you call C++ functions from your C code does not make setjmp and longjmp more unsafe than they always are.
What's important is that if your library allocates resources you must have recovery code in place to ensure that those are released properly after longjmp is called. While this is likely easy for your own allocations, it may be hard or impossible for the C++ library depending on how the C interface you use is structured.
一般来说,
setjmp
/longjmp
在 C++ 中使用不安全。它们有效地复制了异常的行为,但没有正确展开堆栈(例如,它们不会为强制退出的堆栈帧上的对象运行析构函数)。如果可能,请使用异常(如果有)。setjmp
/longjmp
are, in general, not safe for use with C++. They effectively replicate the behavior of exceptions, but without unwinding the stack correctly (for instance, they will not run destructors for objects on stack frames that they forcibly exit). Where possible, use exceptions instead if you've got them.嗯,对又不对。
longjmp
通常不会调用析构函数,因此在如下代码中使用它会导致各种不好的事情发生。如果你避免这种情况,应该没问题。 (一般来说,longjmp 不得跳过任何具有非平凡析构函数的对象的活动堆栈帧。)
Well, right and not right.
longjmp
will in general not call destructors, so using it in a code like the following:will make all sorts of bad things happen. If you avoid such situations, you should be OK. (In general, longjmp must not jump across any active stack frames with objects having non-trivial destructors.)