JNI (JAVA Native Interface) 是 Java 与 C 的桥梁,有些时候要用到 JNI :
?访问底层硬件
?提高代码运行效率
简单的整型数据传递
?首先添加环境变量:
?jni.h include=C:\Program Files\Java\jdk1.6.0_13\include
?jni_md.h include=C:\Program Files\Java\jdk1.6.0_13\include\win32
?用 eclipse 编写 Java 代码:D_int.java
Java代码
1.package com.ldq.d_int;
2.
3.public class D_int {
4. static {
5. System.loadLibrary("Factorial");
6. }
7.
8. public native long getFactorial(int num);
9.
10. public static void main(String[] args) {
11. D_int d = new D_int();
12. int num = 10;
13. System.out.println(num + "!=" + d.getFactorial(num));
14. }
15.
16.}
package com.ldq.d_int;
public class D_int {
static {
System.loadLibrary("Factorial");
}
public native long getFactorial(int num);
public static void main(String[] args) {
D_int d = new D_int();
int num = 10;
System.out.println(num + "!=" + d.getFactorial(num));
}
}
?在 bin 目录下,生成头文件 com_ldq_d_int_D_int.h:javah -jni com.ldq.d_int.D_int
C代码
1./* DO NOT EDIT THIS FILE - it is machine generated */
2.#include <jni.h>
3./* Header for class com_ldq_d_int_D_int */
4.
5.#ifndef _Included_com_ldq_d_int_D_int
6.#define _Included_com_ldq_d_int_D_int
7.#ifdef __cplusplus
8.extern "C" {
9.#endif
10./*
11. * Class: com_ldq_d_int_D_int
12. * Method: getFactorial
13. * Signature: (I)J
14. */
15.JNIEXPORT jlong JNICALL Java_com_ldq_d_1int_D_1int_getFactorial
16. (JNIEnv *, jobject, jint);
17.
18.#ifdef __cplusplus
19.}
20.#endif
21.#endif
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_ldq_d_int_D_int */
#ifndef _Included_com_ldq_d_int_D_int
#define _Included_com_ldq_d_int_D_int
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_ldq_d_int_D_int
* Method: getFactorial
* Signature: (I)J
*/
JNIEXPORT jlong JNICALL Java_com_ldq_d_1int_D_1int_getFactorial
(JNIEnv *, jobject, jint);
#ifdef __cplusplus
}
#endif
#endif
?在 bin 目录下新建 Factorial.cpp 文件,并根据上面函数定义,编写代码:
Cpp代码
1.#include "com_ldq_d_int_D_int.h"
2.
3.JNIEXPORT jlong JNICALL Java_com_ldq_d_1int_D_1int_getFactorial (JNIEnv *env, jobject obj, jint num)
4.{
5. int f=1;
6. for(int i=1;i<num+1;i++)
7. {
8. f*=i;
9. }
10. return f;
11.}