A Java Program Call the inherent method,
1. The first step is to write the Java Code :
Class showmsgbox {
Public static void main (string [] ARGs ){
Showmsgbox APP = new showmsgbox ();
App. showmessage ("generated with JNI ");
}
Private native void showmessage (string MSG );
Static {
System. loadlibrary ("msgimpl ");
}
}
Behind the inherent method Declaration, there is a static code block that calls system. loadlibrary () (it can be called at any time, but it is more appropriate)
System. loadlibrary () loads a DLL into the memory and establishes a link with it. The dll must be in your system path or in a directory that contains a Java class file. Based on the specific platform, JVM automatically adds the appropriate file extension.
2. c header file generator: javah
Compile your Java source file and run javah on the compiled. Class file.
Javah-JNI showmsgbox
Javah reads class files and generates a function prototype in the header file of C or C ++ for each inherent method declaration. The following is the output result -- showmsgbox. H source file.
/* Do not edit this file-it is machine generated */
# Include <JNI. h>
/* Header for class showmsgbox */
# Ifndef _ included_showmsgbox
# DEFINE _ included_showmsgbox
# Ifdef _ cplusplus
Extern "C "{
# Endif
/*
* Class: showmsgbox
* Method: showmessage
* Signature: (ljava/lang/string;) V
*/
Jniexport void jnicall java_showmsgbox_showmessage
(Jnienv *, jobject, jstring );
# Ifdef _ cplusplus
}
# Endif
# Endif
From the "# ifdef_cplusplus" pre-processing pilot command, we can see that this file can be compiled by both the C compiler and the C ++ compiler. The first # include command includes
JNI. H-a header file, one of which defines the types used in the rest of the file; jniexport and jnicall are some macros that are appropriately expanded.
3. Implement your own DLL
In VC ++ 6.0, select Win32 dynamic_link library, create msgimpl. cpp, and include showmsgbox. H to the current project. The following content is msgimpl. cpp.
# Include "showmsgbox. H"
# Include <math. h>
# Include <stdio. h>
Jniexport void jnicall java_showmsgbox_showmessage
(Jnienv * ENV, jobject OBJ, jstring s ){
Const char * szstr = (ENV)-> getstringutfchars (S, 0); // Two Parameters
Printf ("string = [% s]", szstr );
Env-> releasestringutfchars (S, szstr); // Two Parameters
}
After compilation, msgimpl is generated in debug. DLL (put it in the directory of the Java class file or in your system path), that is, with showmsgbox. class in the same directory, and then compile and run showmsgbox. java can output string = [generated with JNI] on the console