Java is not perfect. In addition to its shortcomings, Java is much slower than traditional C ++ in terms of running speed. In addition, Java cannot directly access the underlying operating system (such as system hardware ), therefore, Java uses the native method to extend Java
Program .
The native method can be compared to the interface of a Java program and a C program. The implementation steps are as follows:
1. Declare the native () method in Java and compile it;
2. Use javah to generate a. h file;
3. Write a. cpp file to implement the native export method, which must contain the. h file generated in step 2 (note that it contains the JNI. h file in JDK );
4. Compile the. cpp file in step 3 into a dynamic link library file;
5. Use the system. loadlibrary () method in Java to load the dynamic link library file generated in Step 4. This Native () method can be accessed in Java.
Java local method
1. To use a feature of the underlying host platform, this feature cannot be accessed through Java APIs.
2. to access an old system or use an existing library, this system or library is not written in Java.
3. In order to speed up the performance of the programCodeAs a local method.
First write the Java File
/*
* Created on 2005-12-19 author Shaoqi
*/
Package com. hode. hodeframework. modelupdate;
Public class checkfile
{
Public native void displayhelloworld ();
Static
{
System. loadlibrary ("test ");
}
Public static void main (string [] ARGs ){
New checkfile (). displayhelloworld ();
}
}
Then compiled into a class file based on the written file
Then, execute javah-JNI com. hode. hodeframework. modelupdate. checkfile in the class root directory such as classes or bin,
A com_hode_hodeframework_modelupdate_checkfile.h file is obtained in the root directory.
Compile the com_hode_hodeframework_modelupdate_checkfile.c File Based on the header file.
# Include "checkfile. H"
# Include
# Include
Jniexport void jnicall java_com_hode_hodeframework_modelupdate_checkfile_displayhelloworld (jnienv * ENV, jobject OBJ)
{
Printf ("Hello world! /N ");
Return;
}
Compile and generate the DLL file, such as "test. dll". The name is the same as that in system. loadlibrary ("test ").
VC compilation method: CL-I % java_home %/include/Win32-LD com_hode_hodeframework_modelupdate_checkfile.c-fetest. dll
Add the parameter-djava. Library. Path = [DLL storage path] at runtime.