Java Native method, jni instance and common error analysis

Source: Internet
Author: User
Tags visual studio 2010

1. Overview

  Today is looking at Java about calling native code subroutines to get a faster execution time, or you want to use a dedicated third-party library, such as a statistics pack. However, because Java programs are compiled into bytecode, bytecode is interpreted by the Java Runtime System (or dynamically compiled) and it seems impossible to invoke a native code subroutine in a Java program. Fortunately, this conclusion is wrong. Java provides the native keyword, which is used to declare native code methods. Once declared, these methods can be called in a Java program, just as you would call other Java methods.

2.native keyword Usage

  Now that Java provides the native method, how do you do it? Native is used in conjunction with C + + development! Using the native keyword means that this method is a native function, that is, the method is implemented in the C + + language, and is compiled into a DLL, called by Java. The implementation of these functions in the DLL, the JDK source code is not included, you should be invisible. They are also different for different platforms. This is also the underlying mechanism of Java, in fact, Java is on different platforms with different native methods to achieve access to the operating system. Word:

    1. Native is used in collaboration with Java and other languages such as C + +, which means that the implementation of functions after native is not written in Java.
    2. Since it is not Java, then forget the source code, we just need to know that this method has been implemented.
    3. Native means to inform the operating system that this function you must give me to implement as I want to use. So the function of the native keyword is implemented by the operating system, and Java can only be called.
    4. Java is a cross-platform language, since it is a cross-platform, the cost is to sacrifice to the bottom of the control, and Java to achieve the bottom of the control, need some language help, this is the role of native.
3.JNI Introduction

  The native method is implemented through JNI in Java. JNI is the abbreviation for Java Native interface. Starting with Java1.1, the Java Native Interface (JNI) standard becomes part of the Java platform, which allows Java code to interact with code written in other languages. JNI was initially designed for local compiled languages, especially C and C + +, but it does not prevent you from using other languages, as long as the calling convention is supported. Using Java to interact with locally compiled code often loses platform portability. However, in some cases this is acceptable and even necessary, such as using some old libraries, interacting with the hardware, the operating system, or to improve the performance of the program. The JNI standard guarantees at least local code to work with any Java virtual machine implementation.

There are three main technologies for Java to interact with DLLs: JNI, Jawin, and Jacob. JNI (Java Native Interface) is a technique that sun provides to interact with native methods in the system (Java and Native method intermodulation in the Windows\linux system). It can only be implemented by C + + at this time. The latter two are open source projects on SourceForge and are also libraries of applications on Windows systems based on JNI technology. Jacob (Java-combridge) provides the ability of Java programs to invoke methods in Microsoft's COM objects. In addition to COM objects, Jawin (JAVA/WIN32 integration project) can also win32-dll methods in a dynamic-link library. In terms of functionality: Jin>>jawin>jacob. In terms of ease of use, it is the opposite: Jacob>jawin>>jni

  While the JVM encapsulates the actual variability of the various operating systems, it provides JNI technology that enables developers to invoke functions implemented by the operating system-related technologies through Java Programs (code), interacting with other technologies and systems, and using other technologies to implement functionality At the same time, other technologies and systems can invoke the internal implementation of the Java application through the corresponding native interface provided by JNI.

On Windows systems, generally executable applications are based on the native PE structure, and the JVM on Windows is based on the native architecture. Java application architectures are built on top of the JVM.

JNI can be seen as a proxy mode for the application itself. For developers, it is necessary to implement an agent (JNI program) to actually manipulate the target native function, in Java programs The JVM calls the target native function indirectly by loading and invoking this JNI program.

Writing steps for 4.JNI
    1. Write a Java class with the native declaration method, generate the Javawen file
    2. Compile the Java class written using the Javac command to generate a. class file
    3. Generates a. h file by using the Javah-jni Java class name to generate a header file with the extension H.
    4. Implement the Local method using C + + (or another programming language) to create an implementation of the. h file, that is, create a. cpp file to implement the method in the. h file.
    5. Generate a DLL file by generating a dynamic-link library of files written in C + +
5.JNI Instances

  The following are all operations performed under directory: D:\Native, and the benefits of doing so are easy to control. Another requirement is that our Java class does not contain a package name. Otherwise, you will be prompted with an error using the Javah-jni class file name: "Class" cannot be found.

  1. Write the Java class with the native declaration method: Nativedemo.java.
     Public classNativedemo {inti;  Public Static voidMain (string[] args) {Nativedemo ob=NewNativedemo (); OB.I=10; System.out.println ("This is ob.i before the native method:" +OB.I); Ob.test ();//Call a native method.System.out.println ("This was ob.i after the native method:" +OB.I); }        //Declare native method     Public native voidtest (); //load DLL that contains static method    Static{system.loadlibrary ("Nativedemo"); }        }

    When writing Java classes, be sure to take care not to bring the package name. Especially when you use Eclipse to automatically add package names.

  2. Compile the Java class written using the Javac command: D:\native>javac Nativedemo.java. Generate D:\Native\NativeDemo.class after executing the above command
  3. Use the Javah-jni Java class name to generate a header file with the extension h: D:\native>javah-jni Nativedemo. After executing the above command, generate the D:\Native\NativeDemo.h file, which reads as follows:
     /*   do not EDIT this file-it are machine Generated  */  #include  <jni.h >/*   Header for class Nativedemo  */  #ifndef _included_nativedemo#define _included_nativedemo#ifdef __ Cplusplusextern  "C"  {#endif  /*  Span style= "color: #008000;" > * Class:nativedemo * method:test * Signature: () V  */ jniexport  void   Jnicall Java_nativedemo _test (jnienv  * 

    This h file is equivalent to the interface we have in Java, which declares a java_nativedemo_test (jnienv *, Jobject). method, and then implement this method in our native method, that is, we are writing C + + The method name used in the program must be the same as here.

  4. to implement the local method using C + +: Create NATIVEDEMO.C, the code looks like this:
    *this file contains the C version of the test () method*/#include<jni.h>#include"NativeDemo.h"#include<stdio.h>JniexportvoidJnicall Java_nativedemo_test (JNIENV *Env,jobject obj)    {Jclass cls;    Jfieldid FID;        Jint i; printf ("Starting the native method.\n"); CLS= (*env)Getobjectclass (env, obj); FID= (*env)->getfieldid (env, CLS, "I", "I"); if(fid==0) {printf ("Could not get field id.\n"); return; } I= (*env)Getintfield (env, OBJ,FID); printf ("I=%d\n", i); (*env)->setintfield (env,obj,fid,2*i); printf ("Ending the native method.\n"); }


  5. Generate a dynamic connection library for files written in C + +: D:\Program files\java\jdk1.7.0_07\include\jni.h and D:\Program files\java\jdk1.7.0_07\include\ Win32\jni_md.h This two files are copied to the D:\Native\ directory.
  6. Execute cl/ld:d:\native\nativedemo.c get NativeDemo.dll file. In order to use the CL command in Visual Studio 2010, you must open the Visual Studio command line, as shown in:

If your computer is a 32 operating system, use the red box to compile, if the 64-bit operating system chooses the one below the red box to compile. Here's how:

After executing the above command, the D:\Program Files\Microsoft Visual Studio 10.0\VC can see the resulting four files, respectively:

    • NativeDemo.dll
    • Nativedemo.exp
    • NativeDemo.lib
    • Nativedemo.obj

Copy the NativeDemo.dll into the D:\Native\ directory.

7. Execute class to get results

Run in cmd: in the D:\Native\ directory: Java nativedemo. Run the results.

7. Precautions:
    1. Java source files do not have a package name. I tested no package name to successfully generate H file. Java source file with package name when the H file is generated, it is wrong to find the class file for "class name".
    2. When copying jni.h and jni_md.h to the D:\Native\ directory, an error occurred at compile time: fatal error C1083:cannot open include file: ' Jni.h '. This time the solution is: Will D:\Program files\java\jdk1.7.0_07\include\jni.h, D:\Program files\java\jdk1.7.0_07\include\win32\jawt_ Md.h, D:\Program files\java\jdk1.7.0_07\include\win32\jni_md.h copy to D:\Program Files\Microsoft Visual Studio 10.0\vc\ The Include\ directory is the perfect solution to this problem.
    3. Compile under the corresponding 32/64 operating system when you use the Visual Studio 2010 command prompt. Otherwise there will be an error.

  

  

Java Native method, jni instance and common error analysis

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.