120 likes | 439 Views
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.
E N D
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 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
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(); }
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"); }
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); }