Java JNI 简介

来源:互联网 发布:万网域名注册官网 编辑:程序博客网 时间:2024/06/08 16:38

      最近Java选修课程布置了一个做系统硬件监测的题目,由于Java作为一种基于JVM的高级语言,没有直接访问到硬件的接口,所以要借助JNI来调用C/C++编写的Dll动态链接库来实现这个功能。下面对JNI的概念以及使用方法做一个简单的介绍,介绍使用方法时忽略了安装Java运行时库以及环境变量配置的步骤,这个可能需要注意一下。

      JNI 是什么

      The Java Native Interface (JNI) is a programming framework that allows Java code running in a Java Virtual Machine (JVM) to call and to be called by native applications (programs specific to a hardware and operating system platform) and libraries written in other languages, such as C, C++ and assembly.

      JNI allows one to write native methods to handle situations when an application cannot be written entirely in the Java programming language, e.g. when the standard Java class library does not support the platform-specific features or program library. It is also used to modify an existing application—written in another programming language—to be accessible to Java applications. Many of the standard library classes depend on JNI to provide functionality to the developer and the user, e.g. file I/O and sound capabilities. Including performance- and platform-sensitive API implementations in the standard library allows all Java applications to access this functionality in a safe and platform-independent manner.

      The JNI framework lets a native method utilize Java objects in the same way that Java code uses these objects. A native method can create Java objects and then inspect and use these objects to perform its tasks. A native method can also inspect and use objects created by Java application code.

      JNI is sometimes referred to as the "escape hatch" for Java developers because it allows them to add functionality to their Java application that the standard Java APIs cannot otherwise provide. It can be used to interface with code written in other languages, such as C and C++. It is also used for time-critical calculations or operations like solving complicated mathematical equations, since native code can be faster than JVM code.

      JNI 如何使用

      1)编写调用本地方法的Java类文件

      2)编译JNI格式头文件

 

      3)利用C/C++对头文件实现,生成相应的Dll文件

      JNI C/C++ 头文件

      JNI C/C++ 源文件

      4)将Dll放在环境变量目录或当前目录,调用Java解释器运行上述Java类文件

原创粉丝点击