码迷,mamicode.com
首页 > 编程语言 > 详细

java中native方法的使用

时间:2015-08-12 17:01:20      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:java   native方法   dll文件   

在很多情况下,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新建dll工程)

(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




版权声明:本文为博主原创文章,未经博主允许不得转载。

java中native方法的使用

标签:java   native方法   dll文件   

原文地址:http://blog.csdn.net/zhangpan19910604/article/details/47444139

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!