Ubuntu USES Jni to develop example details

  • 2020-05-12 02:33:44
  • OfStack

1. Write the 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 javac command to generate 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 <jni.h>
/* 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. Wrote Prompt.c documents 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 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

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: