1. Write a Java file in which to declare the native method and load the dynamic link library with a static statement block, the example 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. Invoke the Javac command to generate the Prompt.class file;
Javac Prompt.java
3. Invoke Javah command to generate Prompt.h header file for C program reference:
Javah-jni Prompt
The automatically generated header files are as follows:
/* Do isn't EDIT this file-it is machine generated/*
#include <jni.h>/
* Header for Class Prompt * * *
#if Ndef _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. Write prompt.c files to achieve specific functions:
#include <jni.h>
#include <stdio.h>
#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 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
Thank you for reading, I hope to help you, thank you for your support for this site!