首页 > 编程语言 > 详细

JNI测试-java调用c算法并返回java调用处-1到20阶乘的和

时间:2014-12-05 10:44:33      阅读:221      评论:0      收藏:0      [点我收藏+]

一,java端:

  定义native方法, ‘public native long factorial(int n);‘, 该方法用c/c++实现,计算‘1到20阶乘的和‘,参数中‘int n‘是前n项的阶乘的和(这里是20).返回计算结果,并返回java调用处.

代码为:

bubuko.com,布布扣
 1 public class FactorialJava {
 2 
 3     public native long factorial(int n);
 4 
 5     //evaluate the elapse time.and the execution result.
 6     public long elapse() {
 7         long start = System.currentTimeMillis();
 8 
 9         // code executing time.
10         long sumResult = factorial(20);
11 
12         System.out.println("sum_result:" + sumResult);
13 
14         long end = System.currentTimeMillis();
15         return end - start;
16     }
17 
18     //load the dll library before executing conductive code.
19     static {
20         System.loadLibrary("FactorialDll");
21     }
22 
23     public static void main(String[] args) {
24         FactorialJava fac = new FactorialJava();
25         System.out.println("耗时: " + fac.elapse() + " 毫秒");
26     }
27 
28 }
View Code

二,c/c++在vs中新建一个能产生dll动态链接库的项目,并实现java中定义的native方法.代码如下:

bubuko.com,布布扣
 1 jlong
 2 recesive_fac(jint n) {
 3     if(n == 1)
 4         return 1;
 5     else
 6     {
 7         return n * recesive_fac(n - 1);
 8     }
 9 }
10 
11 //使用jni循环递归过程,将结果返回java调用处.
12 JNIEXPORT jlong JNICALL Java_FactorialJava_factorial
13   (JNIEnv *env, jobject obj, jint n) {
14     jlong sum = 0;    
15     //const jint n = 20;
16     for(int i = 1; i <= n; i++) {
17         sum += recesive_fac(i);
18     }
19     
20     return sum;
21 }
View Code

其中,调用过程需要引入的额外头文件,配置eclipse中的classpath的步骤在博客中的 java JNI 的实现(1)-又进一步加深对JVM实现的理解 中.

JNI测试-java调用c算法并返回java调用处-1到20阶乘的和

原文:http://www.cnblogs.com/listened/p/4145909.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!