One, Java side:
Define the native method, ' public native long factorial (int n); ', the method is implemented in C + +, computes ' 1 to 20 factorial and ', the argument ' int n ' is the factorial of the first n and (here is 20). Returns the result of the calculation, and return to the Java call.
The code is:
1 Public classFactorialjava {2 3 Public native LongFactorial (intn);4 5 //evaluate the elapse time.and the execution result.6 Public Longelapse () {7 LongStart =System.currenttimemillis ();8 9 //code executing time.Ten LongSumresult = factorial (20); One ASystem.out.println ("Sum_result:" +sumresult); - - LongEnd =System.currenttimemillis (); the returnEnd-start; - } - - //load the DLL library before executing conductive code. + Static { -System.loadlibrary ("Factorialdll"); + } A at Public Static voidMain (string[] args) { -Factorialjava FAC =NewFactorialjava (); -System.out.println ("Time-consuming:" + fac.elapse () + "milliseconds"); - } - -}
View Code
b/C + + creates a project in VS that can generate DLL dynamic-link libraries and implements the native method defined in Java. The code is as follows:
1 Jlong2 Recesive_fac (jint N) {3 if(n = = 1)4 return1;5 Else6 {7 returnn * RECESIVE_FAC (n-1);8 }9 }Ten One //Use the JNI loop recursion procedure to return the result to the Java call. A jniexport jlong jnicall java_factorialjava_factorial -(JNIENV *env, Jobject obj, Jint N) { -Jlong sum = 0; the //const Jint n =; - for(inti = 1; I <= N; i++) { -Sum + =RECESIVE_FAC (i); - } + - returnsum; +}
View Code
Where the calling process needs to introduce additional header files, configure the classpath steps in Eclipse in the blog with the implementation of Java JNI (1)-and further deepen the understanding of the JVM implementation.
The JNI test-java calls the C algorithm and returns the 1 to 20 factorial of the Java call and