JNI或Runtime.exec()? [英] JNI or Runtime.exec()?

查看:102
本文介绍了JNI或Runtime.exec()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从Java类中调用以C语言实现的RPC客户端.

I need to call a RPC client which is implemented in C from a Java class.

交互仅是一种方式(即Java必须调用C中的特定函数,而C无需将任何内容返回给调用Java代码.

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.

有人可以向我解释专业人士吗?使用两种类型(JNI/Runtime.exec)中的缺点?而对于我的情况而言,哪个是最佳选择?

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?

推荐答案

Runtime.exec()将为每个调用启动一个单独的进程.您的Java调用者需要使用每个进程的输出.

Runtime.exec() will launch a separate process for each call. Your Java caller needs to consume the output of each process.

JNI将需要一个本机的,动态链接的库.根据您的操作系统,您可能需要显式导出功能.您将使用本机"方法定义Java类,使用javah生成C头文件/存根文件,并通过调用C客户端函数来实现本机方法.

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()可能消耗最多的资源.我个人将使用对本机代码的进程内调用.

Runtime.exec() probably consumes the most resources. I personally would use an in-process call to native code.

考虑使用 JNA 代替JNI, 从Java轻松调用C函数,而无需特殊的本地粘合层.您的C函数必须位于本地的动态链接库中.在Java中,您声明其签名,加载库并调用函数.

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.

对于Windows DLL,请注意,您需要导出函数以使其可以从DLL外部使用.

For Windows DLLs, be aware that you need to export functions for them to be available from outside the DLL.

这篇关于JNI或Runtime.exec()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆