2008年4月28日星期一

jni 简介

1.简介

  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

  2.JNI的书写步骤

  编写带有native声明的方法的java类

  使用javac命令编译所编写的java类

  使用javah ?jni java类名生成扩展名为h的头文件

  使用C/C++实现本地方法

  将C/C++编写的文件生成动态连接库

  ok

  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 ?jni HelloWorld

  头文件的内容:

  /* DO NOT EDIT THIS FILE - it is machine generated */

  #include <jni.h>

  /* Header for class HelloWorld */

  #ifndef _Included_HelloWorld

  #define _Included_HelloWorld

  #ifdef __cplusplus

  extern "C" {

  

没有评论: