1. Write a Java file, declare the native method in it, and load the dynamic link library through the static statement block. The sample Prompt. java code is as follows: classPrompt {privatenativeStringgetLine (Stringprompt); publicstaticvoidmain
1. Write a Java file, declare the native method in it, and load the dynamic link library through the static statement block. The sample Prompt. java code is as follows:
Class Prompt {
Private native String getLine (String prompt );
Public static void main (String args []) {
Prompt p = new Prompt ();
String input = p. getLine ("Type a line :");
System. out. println ("User typed:" + input );
}
Static {
System. loadLibrary ("Prompt ");
}
}
2. Call the javac command to generate the Prompt. class file;
Javac Prompt. java
3. Call the javah command to generate the Prompt. h header file for reference by the C program:
Javah-jni Prompt
The automatically generated header file is as follows:
/* Do not edit this file-it is machine generated */
# Include
/* Header for class Prompt */
# Ifndef _ Included_Prompt
# Define _ Included_Prompt
# Ifdef _ cplusplus
Extern "C "{
# Endif
/*
* Class: Prompt
* Method: getLine
* Signature: (Ljava/lang/String;) Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_Prompt_getLine
(JNIEnv *, jobject, jstring );
# Ifdef _ cplusplus
}
# Endif
# Endif
4. Compile the Prompt. c file to implement specific functions:
# Include
# Include
# Include "Prompt. h"
JNIEXPORT void JNICALL
Java_Prompt_getLine (JNIEnv * env, jobject obj, jstring prompt)
{
Char buf [128];
Const jbyte * str;
Str = (* env)-> GetStringUTFChars (env, prompt, NULL );
If (str = NULL ){
Return NULL;
}
Printf ("% s", str );
(* Env)-> ReleaseStringUTFChars (env, prompt, str );
Scanf ("% s", buf );
Return (* env)-> NewStringUTF (env, buf );
}
5. Compile the dynamic library libPrompt. so;
Gcc-shared-fpic-I/usr/lib/jvm/java-6-sun-1.6.0.26/include-I/usr/lib/jvm/java-6-sun-1.6.0.26/ include/linux Prompt. c-o libPrompt. so
6. Run.
Java Prompt