1 / 7

Java Native Interface Tutorial

Java Native Interface Tutorial. Xiaolin Li Rutgers. JVM. JNI. Motivation. A seamless bridge between Java and native implementation in C, C++ or other languages. Java Application and Library. Native Application And Library. Host Environment (OS). Getting Started.

duane
Download Presentation

Java Native Interface Tutorial

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Native Interface Tutorial Xiaolin Li Rutgers

  2. JVM JNI Motivation • A seamless bridge between Java and native implementation in C, C++ or other languages Java Application and Library Native Application And Library Host Environment (OS)

  3. Getting Started 1. Create a Java class that declares the native method 2. Compile (javac) Hello.java 3. Javah –jni Hello Hello.class Hello.h 6. Done Run the java application Java Hello Hello.c 4. Write C impl 5. Compile C code and generate native lib Hello.dll or libhello.so

  4. Hello World // Hello.java public class Hello { static { String libpath = System.getProperty("java.library.path"); libpath += ":."; System.setProperty("java.library.path", libpath); System.loadLibrary("Hello"); } public static void main(String[] args) { Hello hello = new Hello(); hello.Hello(); } private native void Hello(); }

  5. Hello World // Hello.c #include <stdio.h> #include <math.h> #include "Hello.h" JNIEXPORT void JNICALL Java_Hello_hello(JNIEnv* env, jobject obj) { printf("Hello, World.\n"); }

  6. Executable Java Application int main(int argc, char * argv[]) { JNIEnv *env; JavaVM *jvm; jint res; jclass cls; jmethodID mid; // 1. create JVM res = JNI_CreateJavaVM(&jvm, (void**) &env, &vm_args); // 2. find and load the Java application cls = (*env)->FindClass(env, "Hello"); mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V"); // 3. execute it (*env)->CallStaticVoidMethod(env, cls, mid, args); (*jvm)->DestroyJavaVM(jvm); }

  7. Thank You

More Related