java native code_java中native方法的使用

在很多情况下,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

/* 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

#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就会出现如下结果

info-detail-981234.html

info-detail-981234.html

三、总结:

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

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

info-detail-981234.html





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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值