JNI (JAVA Native Interface) 是 Java 与 C 的桥梁,有些时候要用到 JNI :

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.}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值