Ubuntu Use JNI Development example detailed _java

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.