Create a Test folder and create a java class Test. java. The Code is as follows:
Public class Test {
Static {
System. loadLibrary ("Test ");
}
Public native int test ();
Public static void main (String [] args ){
Test test = new Test ();
System. out. println (test. test ());
}
}
Go to cmd and enter this directory. After java Test. java is compiled, javah-jni Test generates Test. h
This is a C header file with the following content:
/* Do not edit this file-it is machine generated */
# Include <jni. h>
/* Header for class Test */
# Ifndef _ Included_Test
# Define _ Included_Test
# Ifdef _ cplusplus
Extern "C "{
# Endif
/*
* Class: Test
* Method: test
* Signature: () I
*/
JNIEXPORT jint JNICALL Java_Test_test
(JNIEnv *, jobject );
# Ifdef _ cplusplus
}
# Endif
# Endif
The preceding include <jni. h> can be changed to include "jni. h". The jni. h file is in the include folder of the jdk directory and can be copied to the current Test directory.
Then create the C code file. The Test. c code is as follows:
# Include "test. h"
JNIEXPORT jint JNICALL Java_Test_test
(JNIEnv * env, jobject obj)
{
Return 1;
}
Then use the cl command (cl is the C compiler compilation command) to compile Test. c. The command is as follows:
Cl-Id: \ jdk \ include \ win32-LD Test. c (myDll. lib)-FeTest. dll
(MyDll. lib) is the code library used in your C code file. In this example, it is useless and does not need to be imported. The path specified by-Id indicates the header file required by jni. h file location. -LD indicates that the dynamic link library (dll) is to be generated.
Finally, let's Test the java Test running Test. class in the Test directory.