Java can access the local dynamic connection library through the JNI interface to expand Java functions. To use the Java JNI interface, perform the following steps:
(1) Write Java code, indicating the local dynamic connection library to be accessed and local methods;
(2) Compile the Java code to obtain the. Class file;
(3) Use javah-JNI to generate C language. h file corresponding to this class;
(4) use C/C ++ to implement (3) the functions declared in the. h file generated;
(5) compile C/C ++ to generate a dynamic Connection Library for the code.
This article uses a simple helloworld example to demonstrate how to use JNI.
(1) Write Java code
Public class helloworld
{
Public native void sayhello (string name );
Static
{
System. loadlibrary ("examdll ");
}
Public static void main (string [] argv)
{
Helloworld Hello = new helloworld ();
Hello. sayhello ("myname ");
}
}
(2) compile Java code
Javac helloworld. Java
(3) generate the function header file
Javah-classpath. helloworld
The file content is as follows:
/* Do not edit this file-it is machine generated */
# Include <JNI. h>
/* Header for class helloworld */
# Ifndef _ included_helloworld
# DEFINE _ included_helloworld
# Ifdef _ cplusplus
Extern "C "{
# Endif
/*
* Class: helloworld
* Method: sayhello
* Signature: (ljava/lang/string;) V
*/
Jniexport void jnicall java_helloworld_sayhello
(Jnienv *, jobject, jstring );
# Ifdef _ cplusplus
}
# Endif
# Endif
(4) implement the above functions in VC
# Include "helloworld. H"
# Include <stdio. h>
# Include <string. h>
Void jnicall java_helloworld_sayhello (jnienv * ENV, jobject OBJ, jstring Str)
{
Jboolean B = true;
Char s [80];
Memset (S, 0, sizeof (s ));
Strcpy_s (S, (char *) ENV-> getstringutfchars (STR, & B ));
Printf ("Hello, % s", S );
Env-> releasestringutfchars (STR, null );
}
* *** This is the key to JNI: Through ENV, we can use a set of function operation and conversion function parameters provided by Java.
(5) Compile the VC project to obtain the dynamic Connection Library examdll. dll.
==========================================
Appendix: some examples of how to operate and return Java parameters and types are provided in this article:
Http://blog.sina.com.cn/s/blog_548cc485010005ct.html