当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
JNIjava本地接口
发布时间:2011/1/9 13:59:55 来源:城市学习网 编辑:ziteng

  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”是动态库的名字。

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved