学习了一下jni,发表文章的时候不知道该选什么好了,不知道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" {
#endif
/*
* class: helloworld
* method: displayhelloworld
* signature: ()v
*/
jniexport void jnicall java_helloworld_displayhelloworld
(jnienv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
(这里我们可以这样理解:这个h文件相当于我们在java里面的接口,这里声明了一个java_helloworld_displayhelloworld (jnienv *, jobject);方法,然后在我们的本地方法里面实现这个方法,也就是说我们在编写c/c++程序的时候所使用的方法名必须和这里的一致)。
4) 编写本地方法
实现和由javah命令生成的头文件里面声明的方法名相同的方法。
代码2:
1 #include <jni.h>
2 #include "helloworld.h"
3 #include <stdio.h>
4 jniexport void jnicall java_helloworld_displayhelloworld(jnienv *env, jobject obj)
{
printf("hello world!/n");
return;
}
注意代码2中的第1行,需要将jni.h(该文件可以在%java_home%/include文件夹下面找到)文件引入,因为在程序中的jnienv、jobject等类型都是在该头文件中定义的;另外在第2行需要将helloworld.h头文件引入(我是这么理解的:相当于我们在编写java程序的时候,实现一个接口的话需要声明才可以,这里就是将helloworld.h头文件里面声明的方法加以实现。当然不一定是这样)。然后保存为helloworldimpl.c就ok了。
5) 生成动态库
这里以在windows中为例,需要生成dll文件。在保存helloworldimpl.c文件夹下面,使用vc的编译器cl成。
cl -i%java_home%/include -i%java_home%/include/win32 -ld helloworldimp.c -fehello.dll
注意:生成的dll文件名在选项-fe后面配置,这里是hello,因为在helloworld.java文件中我们loadlibary的时候使用的名字是hello。当然这里修改之后那里也需要修改。另外需要将-i%java_home%/include -i%java_home%/include/win32参数加上,因为在第四步里面编写本地方法的时候引入了jni.h文件。
6) 运行程序
java helloworld就ok。^_^
闽公网安备 35060202000074号