您的位置:首页 > 编程语言 > Java开发

java中native方法的使用

2017-07-29 09:40 288 查看
在非常多情况下,java须要调用其它语言的代码,比方c的代码。那么这个时候java中native方法就发挥作用了。以下就介绍native方法的使用。

一、JNI使用流程

a.编写带有native声明的方法的Java类

b.使用javac命令编译编写的Java类

c.使用java -jni ****来生成后缀名为.h的头文件

d.使用其它语言(C、C++)实现本地方法

e.将本地方法编写的文件生成动态链接库

二、实践

1、编写类代码

package com.sunny.demo;

public class Demo01 {
public native void hello();//没有实现

static{
System.loadLibrary("hello");//在类载入的 时候载入dll
}

public static void main(String[] args){

new Demo01().hello();
}

}


2、编译

javac com/sunny/demo/Demo01.java(注意,我这里是带包编译)

3、生成.h文件

javah -jni com.sunny.demo.Demo01(注意。头文件生成文件夹的位置。不知.java文件的位置,而在和包同级文件夹中,这里生成的文件名称为com_sunny_demo_Demo01.h)

4、用c实现hello方法(vc++6.0新建dllproject)

(1)当中com_sunny_demo_Demo01.h中代码例如以下(javah自己主动生成的)

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_sunny_demo_Demo01 */

#ifndef _Included_com_sunny_demo_Demo01
#define _Included_com_sunny_demo_Demo01
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     com_sunny_demo_Demo01
* Method:    hello
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_sunny_demo_Demo01_hello
(JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif


(2).c文件,实现hello方法

#include<stdio.h>
#include"hello.h"
JNIEXPORT void JNICALL Java_com_sunny_demo_Demo01_hello(JNIEnv * a, jobject b){
printf("hello world");
}

(3)用VC++6.0编译一下在debug文件夹中就生成好了dll文件。

说明:编译时假设产生例如以下错误:fatal error C1083: Cannot open include file: 'jni.h': No such file or directory。说明没有找到jni.h。到jdk的安装文件夹 include/jni.h;win32/jni_md.h;win32/jawt_md.h这3个文件复制到vc的安装文件夹include中

5.将dll放到生成.h的那一集文件夹中。执行java com.sunny.demo.Demo01就会出现例如以下结果

三、总结:

上面的样例中,我是带包编译的,所以文件存放和生成的位置一定要注意,在java层面我们仅仅须要dll文件,.h和.cd 文件的目的仅仅是为了生成dll文件.最后给出我代码的文件夹结果

.h文件是javah生成的,dll文件是应该放的位置(假设不放在这个位置。执行报错,找不到hello这个库)

dll參考文章:http://www.cnblogs.com/chio/archive/2007/11/03/948480.html

external c :http://www.cnblogs.com/rollenholt/archive/2012/03/20/2409046.html

java native文章: http://blog.163.com/yueyemaitian@126/blog/static/21475796200701491621267


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: