JNI (Java Native Interface)是什么


 JNI是Java Native Interface的缩写。从Java 1.1开始,Java Native Interface (JNI)标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI一开始是为了本地已编译语言,尤其是C和C++而设计的,但是它并不妨碍你使用其他语言,只要调用约定受支持就可以了。

      使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的,比如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少保证本地代码能工作在任何Java 虚拟机实现下。


一、JNI(Java Native Interface)的设计目的

      ·The standard Java class library may not support the platform-dependent features needed by your application.
      ·You may already have a library or application written in another programming language and you wish to make it accessible to Java applications
      ·You may want to implement a small portion of time-critical code in a lower-level programming language, such as assembly, and then have your Java application call these functions


二、JNI(Java Native Interface)的书写步骤

      ·编写带有native声明的方法的java类
      ·使用javac命令编译所编写的java类
      ·使用javah ?jni java类名生成扩展名为h的头文件
      ·使用C/C++实现本地方法
      ·将C/C++编写的文件生成动态连接库


1) 编写java程序:
这里以HelloWorld为例。
代码1:

class HelloWorld {
   
public native void displayHelloWorld();

 
static {
          System.loadLibrary(
"hello");
       }
      

      
public static void main(String[] args) {
         
new HelloWorld().displayHelloWorld();
      }

}


声明native方法:如果你想将一个方法做为一个本地方法的话,那么你就必须声明改方法为native的,并且不能实现。其中方法的参数和返回值在后面讲述。
Load动态库:System.loadLibrary("hello");加载动态库(我们可以这样理解:我们的方法displayHelloWorld()没有实现,但是我们在下面就直接使用了,所以必须在使用之前对它进行初始化)这里一般是以static块进行加载的。同时需要注意的是System.loadLibrary();的参数“hello”是动态库的名字。
main()方法是函数得入口点。

2) 编译
javac HelloWorld.java


3) 生成扩展名为h的头文件
javah  HelloWorld

头文件的内容:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include 
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorld
* Method: displayHelloWorld
* Signature: ()V
*/

JNIEXPORT 
void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *, jobject);

#ifdef __cplusplus
}

#endif
#endif

(这里我们可以这样理解:这个h文件相当于我们在java里面的接口,这里声明了一个Java_HelloWorld_displayHelloWorld (JNIEnv *, jobject);方法,然后在我们的本地方法里面实现这个方法,也就是说我们在编写C/C++程序的时候所使用的方法名必须和这里的一致)。

  • 1
  • 2
  • 3
  • 4
  • 5
  • 下一页

相关内容