JNI is short for J Ava Native Interface.
Since Java 1.1, the Java Native Interface (JNI) standard has become part of the Java platform. It allows Java code to interact with code written in other languages. JNI was initially designed for locally compiled languages, especially C and C ++, but it does not prevent you from using other languages, as long as the call conventions are supported.
Using Java to interact with locally compiled code usually results in loss of platform portability. However, in some cases
This is acceptable or even necessary. For example, you can use old libraries to interact with hardware and operating systems, or to improve program performance. The JNI standard should at least ensure that local code can work under any Java Virtual Machine implementation.
Writing steps of JNI (Java Native Interface)
· Compile a Java class with native declarations
· Use the javac command to compile the compiled Java class
· Use javah? JNI Java class names generate header files with the extension H
· Use C/C ++ (or other programming languages) to implement local methods
· Generate a dynamic connection library for files written in C/C ++
1) Compile a Java program:
The following uses helloworld as an example.
Code 1:
Class helloworld {<br/> Public native void displayhelloworld (); <br/> static {<br/> system. loadlibrary ("hello"); <br/>}< br/> Public static void main (string [] ARGs) {<br/> New helloworld (). displayhelloworld (); <br/>}< br/>}
Declare native method: If you want to use a method as a local method, you must declare the method to native and cannot implement it. The parameters and return values of the method are described later.
Load dynamic library: system. loadlibrary ("hello"); load the dynamic library (we can understand this: our method displayhelloworld () is not implemented, but we use it directly below, therefore, it must be initialized before use.) Static blocks are usually used for loading. Note that the parameter "hello" of system. loadlibrary (); is the name of the dynamic library.
Main () method
2) There is nothing to say about compilation.
Javac helloworld. Java
3) generate a header file with the extension of H
Javah? JNI helloworld
Header file content:
/* Do not edit this file-it is machine generated */<br/> # include <br/>/* Header for class helloworld */<br/> # ifndef _ included_helloworld <br/> # DEFINE _ included_helloworld <br/> # ifdef _ cplusplus <br/> extern "C" {<br/> # endif <br/>/* <br /> * class: helloworld <br/> * method: displayhelloworld <br/> * Signature :() v <br/> */<br/> jniexport void jnicall java_helloworld_displayhelloworld <br/> (jnienv *, jobject ); <br/> # ifdef _ cplusplus <br/>}< br/> # endif <br/> # endif
(This can be understood as follows: This H file is equivalent to our interface in Java. Here we declare a java_helloworld_displayhelloworld (jnienv *, jobject); method, then implement this method in our local method, that is to say, the method name we used when writing the C/C ++ program must be consistent with the method name here ).
4) Compile local methods
Implement the same method as the method name declared in the header file generated by the javah command.
Code 2:
# Include <br/> # include "helloworld. H "<br/> # include <br/> jniexport void jnicall java_helloworld_displayhelloworld (jnienv * ENV, jobject OBJ) <br/>{< br/> printf (" Hello world! /N "); <br/> return; <br/>}
Note that line 1st in Code 2 requires JNI. H (this file can be found under the % java_home %/include folder) file introduction, because the types of jnienv and jobject in the program are defined in this header file; in addition, the helloworld. h header file introduction (I understand this as follows: It is equivalent that we can declare an interface when writing a Java program. Here we will introduce helloworld. h. The methods declared in the header file are implemented. Of course not necessarily ). Then save it as helloworldimpl. C and then OK.
5) generate a dynamic library
Here, we use Windows as an example to generate a DLL file. Use the VC compiler Cl to save the helloworldimpl. c folder.
CL-I % java_home %/include/Win32-LD helloworldimp. C-fehello. dll
Note: The generated DLL file name is configured after option-Fe. Here is hello, because the name used for loadlibary in the helloworld. Java file is hello. Of course, after modification, it also needs to be modified. In addition, you need to add the-I % java_home %/include/Win32 parameter, because the JNI. H file is introduced when compiling the local method in step 4.
6) run the program
Java helloworld is OK.
Issues to be considered in JNI (Java Native Interface) calls
I had some questions when I used JNI for the first time. Later I was able to solve these problems one by one. The following are my notes:
1. How is Java and C interconnected?
In fact, the main reason for the inability to communicate is the data type problem. JNI solves this problem. For example, the jstring data type in the C file is the string object passed in by Java, after the conversion of the JNI function, it can become the char * of C *.
The following table lists the corresponding data type relationships:
Java local C type description <br/> Boolean jboolean unsigned, 8-bit <br/> byte jbyte unsigned, 8-bit <br/> char jchar unsigned, 16-bit <br/> short jshort signed, 16-bit <br/> int jint signed, 32-bit <br/> long jlong signed, 64-bit <br/> float jfloat 32-bit <br/> double jdouble 64-bit <br/> void N/
2. How to convert the string parameter passed in by Java to the char * of C and then use it?
The string parameter passed in by Java is converted to the Data Type of jstring by JNI in the C file. Declare char * test in the C file, and then test = (char *) (* env) -> getstringutfchars (ENV, jstring, null); Note: after the test is used, the VM platform-related code is notified that no access is required (* env)-> releasestringutfchars (ENV, jstring, test );
3. Pass the buffer of a char * obtained in C to Java?
If this char * is a general string, it can be returned as a string. If it is a buffer containing '/0', it is best to use bytearray for outgoing transmission, because the length of copy can be set. If it is copied to string, it may be truncated to'/0.
There are two ways to pass the data:
One is to directly create a byte array in JNI, and then call the function (* env)-> setbytearrayregion (ENV, bytearray, 0, Len, buffer ); copy the buffer value to bytearray, and the function can return bytearray directly.
One is the return error code. The data is transmitted as the parameter, but the basic data type of Java is to pass the value, and the object is to pass the reference, use a class package to package the byte array to be transmitted, as shown below:
Class retobj
{
Public byte [] bytearray;
}
This object is transmitted as the retobj parameter of the function. The following function is used to assign values to the byte array in retobj to facilitate the transfer. The Code is as follows:
Jclass CLS; <br/> jfieldid FID; <br/> jbytearray bytearray; <br/> bytearray = (* env)-> newbytearray (ENV, Len ); <br/> (* env)-> setbytearrayregion (ENV, bytearray, 0, Len, buffer); <br/> CLS = (* env)-> getobjectclass (ENV, retobj); <br/> FID = (* env)-> getfieldid (ENV, CLS, "retbytes", "[B"]); <br/> (* env) -> setobjectfield (ENV, retobj, FID, bytearray );
4. I don't know how much buffer is occupied. How can I transfer it out?
In the jni c file, the new output space is passed out. If Java data is not initialized, point to the space passed out.