JNI allows us to invoke the functionality of the local library in Java code.
Let's take a look at the JNI simple way to use
- Creating a Java-side interface
1 Public classJniiterface {2 3 //Import the final generated DLL file4 Static {5System.loadlibrary ("Jnidemo");6 }7 8 //declaring an interface implemented in a DLL file9 Public native intMyMethod ();Ten One Public native intAddintXinty); A}
2. Generate the header file for the C corresponding to the interface
The Jniiterface class created above, the path to the Jniiterface. class file: \jnidemo\bin\base\jniiterface. class
Execute command under the Bin directory in the project directory: Javah-classpath. -jni base. Jniiterface
The base_jniiterface.h file is then generated in the \jnidemo\bin\ directory
3. Writing an implementation of an interface using Visual Studio
To create a C project, proceed as follows:
The first step:
Step Two:
Part III:
Import the required header files
The header file generated by the second step above, and the jni.h under the Include directory under the JDK root directory, and
The Jni_md.h file under the Win32 directory of the include is copied to the header file directory under the project directory
Create a feature implementation file
Right-click on the source file in the project directory and tap Add-"class
and write the following code:
1#include"base_jniiterface.h"2#include"jni.h"3#include <stdio.h>4 5 jniexport jint jnicall java_base_jniiterface_mymethod6(JNIENV *, Jobject) {7printf"successfully implement JNI test demo");8 return 0;9 }Ten One jniexport jint jnicall java_base_jniiterface_add A(JNIENV *, Jobject, jint A, jint b) { - returnA +b; -}
4. Generating DLL files
Right-click on the solution in the project catalog, select Properties, and make the project as shown
After compiling the project, it will become a DLL file under the release directory of the project directory.
5. Configuring the DLL file to Java engineering
First put the DLL file in the Java Project root directory under the Lib directory
Then follow the steps below to add the DLL file as a native library into the project
Edit the native library location as shown, then select the folder where the native library is located in the popup screen:
6. Write test class to verify if JNI is successfully applied
1 Public classHellojni {2 3 Public Static voidMain (string[] args) {4Jniiterface HW =Newjniiterface ();5 intt = Hw.add (3, 7);6 ints =HW. MyMethod ();7 System.out.println (t);8 System.out.println (s);9 }Ten}
The test results after the run are as follows:
Ten 0 success ?? Jni?? DEMO
The most basic steps for using JNI are documented above.
Further exploration is needed on how to use the functionality of a third-party DLL file that has already been written, such as a system DLL file.
Reference article: http://www.runoob.com/w3cnote/jni-getting-started-tutorials.html
How to use JNI