Java local Interface Jni detailed

Source: Internet
Author: User

for JavaProgrammers,Javathe advantages and advantages of the language, I do not want to say, we will naturally say a lot of condoms. But while we asJavaprogrammer, but we have to admitJavaThe language also has some drawbacks of its own. For example, the performance, and the bottom of the deal with its shortcomings. SoJavaprovides a number of local interfaces, his primary role is to provide a standard way forJavaThe program interacts with the native code through the virtual machine, which is what we usually sayJavaLocal Interface (Jni--Java Native Interface)。 It makes the JavaVirtual Machines(VM)the internal runningJavacode can be used with other programming languages, such asC,C++and assembly language) are written to interoperate with applications and libraries. JniThe most important benefit is that it has no effect on the underlyingJavathe implementation of the virtual machine imposes no restrictions. Therefore,JavaVirtual machine vendors can add to a VM without affecting the rest of the virtual machineJnithe support. Programmers only need to write a version of a local application or library to be able to work with all supportedJniof theJavavirtual machines work together. Let's take a look at why we want to interact with the native code:


One: Improve application performance . We know that javais more "advanced" for C + + and assembly language. In fact, the high-level here is simplifying the programmer's work. Many of the underlying things have been done by the Java virtual machine. But after all,Java is a step closer to virtual machines than direct access, so it's a bit slower in terms of performance than these native languages.


Two: Realize some functions related to the bottom . The Java platform provides a standard class library, as well as a powerful API, although it can do most of the functions. But some of the features that deal with the underlying hardware are still not available in the class library provided by the Java API.


Three: Integrate with existing programs written using native code . It is possible to use JNI when the software that is written in native languages such as C or C + + is set up on the operating system.


JNI interface functions and pointers

Platform-related code accesses the Java virtual machine functionality by invoking a JNI function . the JNI function can be obtained through an interface pointer. An interface pointer is a pointer to a pointer array, and each element in the pointer array points to an interface function. Each interface function is in a predetermined offset of the array. describes the organizational structure of interface pointers.

the organization of the JNI interface is similar to a C + + virtual function table or COM interface. The advantage of using an interface table instead of a hard-coded function table is to separate the JNI namespace from the platform-related code. Virtual machines can easily provide multiple versions of the JNI function table. For example, a virtual machine can support the following two JNI function tables:

1) A table on the illegal parameters of a comprehensive check, suitable for debugging procedures;

2) The other table is only JNI The minimum level of inspection required by the specification is therefore highly efficient.

the JNI interface pointer is only valid in the current thread. Therefore, the local method cannot pass an interface pointer from one thread to another. a virtual machine that implements JNI can allocate and store data for a local thread in the area pointed to by the JNI interface pointer.


The local method accepts the JNI interface pin as a parameter. When a virtual machine makes multiple calls to a local method from the same Java thread, the interface pointer that is passed to the local method is guaranteed to be the same. However, a local method can be called by different Java threads, so different JNI interface pointers can be accepted .

1) Writing Java class Code

The methods that require JNI implementations should be declared with the native keyword, in which the System is used. The LoadLibrary () method loads the required dynamic-link libraries, with the following key codes:

Compute.javapublic class compute{public native double sqrt (double params); static{//Call the dynamic link library System. LoadLibrary ("Compute");}}


2) compile into byte code

In this process, the Java compiler ignores the part of the JNI method without the code body because of the native keyword declaration .

3) header file to generate the relevant JNI method

The implementation of this process is generally generated by using the Jlavah-jni * Class (-jni can be omitted), or it can be generated manually, but because the Java virtual machine is based on a certain naming specification to complete the JNI method, so it takes special care to write the header file manually.
The above file produces the header File section code as follows:

Compute.hextern "C" {jniexport jdoublejnicall java_compute_comp (jni-env *, Jobject, Jdoublearray);

jni Java keyword for Java virtual machine recognition; then the caller class name ()


the parameters of the JNI function are also composed of three parts: the first is jnienv *, which is a pointer to the JNI runtime environment, and the second parameter varies with the local method static or non-static one by one non-static local method is a reference to the object , and the second parameter of the static local method is a reference to its Java class, and the remaining parameters correspond to the parameters of the usual Java method, and the parameter types need to be mapped according to certain rules.


4) write the implementation code of the corresponding method

In the coding process, you need to pay attention to the length of variables, such as Java 's integer variable length is a four-bit, and C language is a bit, so carefully check the variable type mapping table, to prevent problems during the transfer of value.


5) Compiling the JNI implementation code into a dynamic-link library

The compilation process is implemented using the C/C + + compiler, and on the Windows platform, the results of compilation and connection are dynamic-link library DLL files. when you want to use the generated dynamic-link library, you need to explicitly call the link library DLL file in the caller class.
After this processing, a Java class that contains a localization method is basically developed.


Appendix: Mapping JAV types to local C types

For ease of use, the following definitions are provided.

#define JNI_FALSE 0

#define JNI_TRUE 1

the jsize integer type is used to describe the primary exponent and size:

typedef jint Jsize;


Trouble shooting

When you use JNI to access native code from a Java program, you encounter many problems. The three most common errors you will encounter are:

1) cannot find dynamic link. The error message that it generates is: Java.lang.UnsatisfiedLinkError. This usually means that the shared library cannot be found, or that a specific native method within the shared library cannot be found.

2) cannot find the shared library file. When loading an inbound file with the system.loadlibrary (String libname) method (the parameter is the file name), make sure that the file name is spelled correctly and that no extension is specified. Also, make sure that the location of the library file is in the classpath so that the JVM can access the library file.

3) Unable to find a method with the specified description. Make sure that your C + + function implementation has the same description as the function description in the header file.


Conclusion

calling C or C + + native code from Java (though not simple) is a well-integrated feature in the Java platform. Although JNI supports C and C + +, the C + + interface is clearer and generally preferableto the C interface. As you've seen, calling C or C + + native code requires a special name for the function and creates a shared library file. When leveraging an existing code base, it is often undesirable to change the code. To avoid this, in C + + , you typically create proxy code or proxy classes that have specialized JNI- required named functions. These functions can then invoke the underlying library functions, and the descriptions and implementations of these library functions remain unchanged.

Java local Interface Jni detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.