jni 入门问题
我开始研究 JNI,据我了解,如果加载的 dll 出现问题,jvm 可能会当场终止。
即进程无法受到保护,例如捕获异常时。
因此,如果我的理解是正确的,我的问题是使用 jni 时是否有针对这种情况的标准方法/模式。
或者换句话说,使用 jni 的流程是否旨在避免这些问题? 或者预计不会出现此类问题?
谢谢。
I started looking into JNI and from what I understand is that if a problem occurs with the loaded dll, the jvm is possible to terminate on the spot.
I.e. the process can not be protected e.g. like when catching an exception.
So if my understanding is correct, my question is if there is a standard approach/pattern for this situation when using jni.
Or to state it differently, are processes using jni designed in way to avoid these issues?
Or such problems are not expected to occur?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,JVM 将终止,这就是 JNI 代码确实难以调试的原因之一。如果您使用 C++ 代码,您可以使用异常,然后将它们映射到 Java 异常,这至少为您提供一定程度的安全性,但对解决不良内存访问等问题没有帮助。
从体系结构的角度来看,我建议解耦尽可能从 JNI 编写代码。创建一个完全可从 C++/C 测试的类/过程结构,并让 JNI 代码仅执行所有转换工作。如果 JVM 崩溃了,您至少知道必须去哪里查找。
Yes, the JVM will just terminate which is one of the reasons why JNI code is really hard to debug. If you are using C++ code you can use exceptions and then map them to a Java exception which at least gives you some level of security but doesn't help with things like bad memory access etc.
From an architecture point of view I suggest to decouple you code from JNI as much as possible. Create a class / procedure structure that is entirely testable from C++/ C and let the JNI code do only all the conversion stuff. If the JVM then crashes you at least know where you have to look.
这些原则与任何多线程 C 应用程序没有什么不同:
Java 虚拟机不会为您的本机代码提供额外的保护,如果它失败或泄漏,您的 VM 也会失败或泄漏。
The principles are no different from any multi-threaded C application:
The Java virtual machine offers you no extra protection for your native code, if it fails or is leaking, your VM will fail or leak.
JNI 库中的错误处理范围与其他库中的错误处理范围完全相同。
您可以使用尝试/捕获。如果您使用的是 Windows,则可以使用 SEH。如果您使用的是 Linux,则可以调用 sigaction。
尽管如此,如果你搞砸了并且出现了 SIGSEGV,那么无论你是否尝试捕获该信号,你的 JVM 都可能会崩溃。
You can have exactly the same spectrum of error handling in a JNI library as in anything else.
You can use try/catch. If you are on Windows, you can use SEH. If you are on Linux, you can call sigaction.
Still, if you mess up and there's a SIGSEGV, your JVM is probably toast whether you try to catch that signal or not.