JNI 还是 Runtime.exec()?
我需要从 Java 类调用用 C 实现的 RPC 客户端。
交互只是 Java 必须调用 C 中特定函数的一种方式,而 C 不需要向调用 Java 代码返回任何内容。
有人可以向我解释一下优点和缺点吗?使用任一类型(JNI/Runtime.exec)的缺点?哪个是适合我的情况的最佳选择?
I need to call a RPC client which is implemented in C from a Java class.
The interaction is one way only(i.e) Java has to invoke specific functions in C, while C need not return anything to the calling Java code.
Can someone explain me the pros & cons in using either of the types (JNI/Runtime.exec)?? and which is the best option for my case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Runtime.exec() 将为每个调用启动一个单独的进程。您的 Java 调用者需要使用每个进程的输出。
JNI 需要一个本机的动态链接库。根据您的操作系统,您可能需要显式导出函数。您可以使用“本机”方法定义 Java 类,使用 javah 生成 C 头文件/存根文件,并通过调用 C 客户端函数来实现本机方法。
Runtime.exec() 可能消耗最多的资源。我个人会使用对本机代码的进程内调用。
不用JNI,可以考虑使用JNA,这样调用方便来自 Java 的 C 函数,无需特设的本机粘合层。您的 C 函数需要位于本机动态链接库中。在 Java 中,您声明它们的签名、加载库并调用函数。
对于 Windows DLL,请注意,您需要导出函数才能从 DLL 外部使用它们。
Runtime.exec() will launch a separate process for each call. Your Java caller needs to consume the output of each process.
JNI would require a native, dynamically linked library. Depending on your operating system, you may need to explicitly export functions. You would define a Java class with "native" methods, generate a C header/stub file with javah, and implement the native methods by calling your C client functions.
Runtime.exec() probably consumes the most resources. I personally would use an in-process call to native code.
Instead of JNI, consider using JNA, which makes it easy to call C functions from Java without an ad hoc native glue layer. Your C functions would need to be in a native, dynamically linked library. In Java, you declare their signatures, load the library, and call the functions.
For Windows DLLs, be aware that you need to export functions for them to be available from outside the DLL.