Basic JNI Call Technology (c/A and Java intermodulation)

Source: Internet
Author: User
Tags naming convention

Notice that I was wrong on the names of the packages that caused the call to fail

1, create the folder Libs/armeabi folder under the project root directory

2, put the so library into the Libs/armeabi folder note:

1, if the use of static registration, please note that the C file in strict accordance with the naming convention Java_packagename_classname_method () the way named

2, establish the same package name in the Android project as in PackageName in the above named rule, and establish the same class name as the classname in the above named rule under this package name

3, in ClassName declaration native method

4, in the program loading so library system.loadlibrary (data/data/xxx.xxx.xxx/lib/xx.so) or system.loadlibrary (xx),

For example: System.loadlibrary (data/data/com.dtbank.app.service/lib/libjnixcld.so);

First, JNI Introduction:

JNI has always been very little attention, but it is a knot in my heart, the last few days just have a little time, so take a look at this aspect of things, sorted out a document, the advent of JNI technology is based on three aspects of the application requirements:

1. Solving performance problems
Java is platform-independent, which makes it one of the main candidates when developing enterprise applications, but the performance factor greatly weakens its competitiveness. For this reason, it is important to improve the performance of Java. Sun and Java supporters have made a lot of effort to improve the speed of Java, most of which focus on the methods and patterns chosen for programming. Because the optimization of algorithm and design pattern is universal, the effective optimization algorithm and design pattern of Java are equally applicable to other compiling languages, so it is not possible to fundamentally change the difference between Java program and compiling language in execution efficiency. Thus, people began to introduce the concept of JIT (Just in Time, Just-in-time compilation). The basic principle is that the Java source code is compiled into platform-independent binary bytecode by the Java compiler first. The system then compiles the Java bytecode into a localized machine code through the JIT compiler before the Java program is actually executed. Finally, the system implements localized machine code, which saves time to interpret bytecode. The advantage of this is that it greatly improves the performance of the Java program, shortens the time to load the program, and saves storage space because the results of the compilation are not saved between programs. The disadvantage is that because the JIT compiler wants to optimize all of the code, it also takes a lot of time.

Dynamic optimization technology is another attempt to improve Java performance. This technique attempts to improve Java performance by compiling Java source programs directly into machine code to take full advantage of Java dynamic compilation and static compilation techniques. This method converts the input Java source or bytecode into highly optimized executable code and dynamic libraries (. dll files in Windows or. so files in Unix). This technology can greatly improve the performance of the program, but it destroys the portability of Java.

JNI (Java Native Interface, Java Localization method) technology from this flash debut. Because the JNI technology is only for some code snippets that seriously affect Java performance, this part may only be a very small part of the source program, so it's almost impossible to take into account the amount of work that part of the code is porting between the mainstream platforms. At the same time, there is no need to worry too much about the type matching problem, we can completely control the code does not appear this error. In addition, there is no need to worry about security control issues because the Java security model has been extended to allow non-system classes to load and invoke local methods. According to the Java specification, from JDK 1. At the beginning of 2, Findclass will try to find the ClassLoader associated with the current local method. If the platform-dependent code belongs to a system class, no class loader is involved; Otherwise, the appropriate class loader is invoked to load and link the named class. In other words, if you call the machine code generated directly in a Java program by the C/C + + language, the security of that part of the code is controlled by the Java Virtual machine.

2. Solve the problem of native platform interface call
Java, which is popular with its cross-platform features, and because of its cross-platform purpose, makes it less powerful and its internal connections to local machines, constraining its functionality. One way to solve Java's local operations is JNI. Java invokes the local method through JNI, and the local method is stored in the form of a library file (in the form of a DLL file on a Windows platform and a so file form on a UNIX machine). By invoking the internal method of the local library file, Java can implement close contact with the local machine and invoke the system-level interface methods.

3. Embedded development Application
"One programming, everywhere use" of the Java Software concept is originally aimed at embedded small devices online, after several setbacks, the current sun has launched the J2ME (Java 2 p1atform Micro Edition) For information appliances, the Java version of the technology is maturing, began to put into use. The orderly openness of Sun's Java Virtual Machine (JVM) technology enables Java software to truly run across platforms, where Java applets can be executed on any hard software system with a JVM. In addition, the Java language itself has the characteristics of security, reliability and portability, it is very advantageous to realize the network equipment such as thin body net, and it has great influence on the embedded equipment, especially the software programming technology of the Internet equipment. Because JNI solves the problem of native platform interface invocation, JNI is also in full swing in the field of embedded development.

Without losing intuition, we first write a jni little example:

Java code public class Hellojni {public native void Displayhellojni ();       static {system.loadlibrary ("Hellojni"); public static void Main (string[] args) {//system.out.println (System.getproperty ("Java.library.path")           );       New Hellojni (). Displayhellojni (); }   }

The corresponding directory execution commands generated in the class file are as follows:
----------------------------------------------------
E:\projects\jni\target\classes>javah Hellojni
----------------------------------------------------

Get C + + file HelloJni.h CPP Code/* Do not EDIT This file-it is machine generated * * #include <jni.h>/* Header for C    Lass Hellojni * * * #ifndef _included_hellojni #define _INCLUDED_HELLOJNI #ifdef __cplusplus extern "C" {#endif * * CLASS:HELLOJNI * METHOD:DISPLAYHELLOJNI * Signature: () V/jniexport void Jnicall java_hellojn      I_displayhellojni (jnienv *, jobject); #ifdef __cplusplus} #endif #endif

The JNI function name is divided into three parts: the first is the Java keyword, which is recognized by the Java Virtual machine, then the caller class name (the fully qualified class name, with the underscore in place of the name separator), and the corresponding method name, which is separated by an underscore between each segment name.


The parameters of the JNI function are also composed of three parts: first is jnienv *, a pointer to the JNI runtime environment, and the second parameter varies with whether the local method is static or non-static one by one the second parameter of a non-static local method is a reference to the object. 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.

To write the implementation class for C + + file HelloJni.h, I am the CPP code that compares common VC6.0 to generate DLL files (helloJni.dll) #include <jni.h> #include "HelloJni.h" #include <stdio.h> jniexport void Jnicall java_hellojni_displayhellojni (jnienv *env, Jobject obj) {printf (       "Hello Dynamic Link Library has been calling!\n");       printf ("Java_hellojni_displayhellojni method has been executed!\n");   Return }

In fact, at this time, our project is still temporarily unable to generate the HelloJni.dll file we want, the problem is in the "#include <jni.h>." Since VC6.0 does not have the "jni.h" file we need, we need to manually join the VC6.0 environment. Under the Java_home path we can find the Include folder where we can find the "jni.h" file we need. To avoid future trouble, all C + + files are taken out and placed under the "%cpp_home%\vc98\include" path. The project is then packaged to get the "HelloJni.dll" file we need.

Place the HelloJni.dll file in the project classes directory and execute the following command:
-----------------------------------------------
E:\projects\jni\target\classes>java Hellojni
-----------------------------------------------

The results of the operation are as follows:
-----------------------------------------------------------------
Hello Dynamic Link Library has been calling!
Java_hellojni_displayhellojni method has been executed!
-----------------------------------------------------------------


But to run the HelloJni.dll file in eclipse, you need to copy the file to the root of the project, or put it in a C:\WINDOWS\system32; C:\WINDOWS, etc. in the directory. Because Eclipse starts by looking at the current root directory when it runs the HelloJni.dll file. If you can't find it, find it in path, so you can also put all of your project's DLL files into a specific directory for easy management of the generated DLL file, and then add that directory to your local path environment variable, which Each time you just need to put the generated DLL file into the path directory, you can access it. Note, if you need to add an environment variable, it's a good idea to restart eclipse after you make sure that Eclipse is able to load into the latest path environment.

Next, refactor the small example:
1. Add a new base class

Java code

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.