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
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
JNI的步骤:
1.编写一个带有 native 的方法,注意这个方法和接口中的方法一样,是没有实现的,同时导入动态库文件。
2.用javac 编译这个类
3.用javah -jni java类名 生成扩展名为h的头文件
4.用c或c++实现本地方法,再这之间首先要导入xx.h头文件
5.将c或c++编写的文件生成动态链接库
编写的java文件如下:
public class Test {
static {
System.loadLibrary("test");
}
public native void test();
public static void main(String[] args) {
Test t = new Test();
t.test();
}
}
static {
System.loadLibrary("test");
}
public native void test();
public static void main(String[] args) {
Test t = new Test();
t.test();
}
}
javah生成的头文件如下:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Test */
#include <jni.h>
/* Header for class Test */
#ifndef _Included_Test
#define _Included_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Test
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Test_test
(JNIEnv *, jobject);
#define _Included_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Test
* Method: test
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_Test_test
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
}
#endif
#endif
最后是Test.c文件:
#include <jni.h>
#include "Test.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Test_test(JNIEnv *env,jobject obj) {
printf("Hello world!/n");
return;
}
#include "Test.h"
#include <stdio.h>
JNIEXPORT void JNICALL Java_Test_test(JNIEnv *env,jobject obj) {
printf("Hello world!/n");
return;
}
通过VC++的cl命令,生成Test.dll文件。
cl -I%java_home%/include -I%java_home%/include/win32 -LD Test.c -FeTest.dll
这里补充一下,System.loadLibrary("xx"); 这里不需要加.dll后缀,而且它不区分大小写。
最后运行 java Test
得到的结果就是:
Hello world!
而这一切不是在java中完成的,是java调用本地文件所得到的。