Rutgers University Excellence Campaign 2/20/2004 Java Native Interface Tutorial Xiaolin Li Rutgers
2 Rutgers University Excellence Campaign Motivation A seamless bridge between Java and native implementation in C, C++ or other languages Java Application and Library JVM JNI Native Application And Library Host Environment (OS)
3 Rutgers University Excellence Campaign Getting Started 1. Create a Java class that declares the native method Hello.java 2. Compile (javac) Hello.class 3. Javah –jni Hello Hello.h 4. Write C impl Hello.c 5. Compile C code and generate native lib Hello.dll or libhello.so 6. Done Run the java application Java Hello
4 Rutgers University Excellence Campaign 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 Rutgers University Excellence Campaign Hello World // Hello.c #include #include "Hello.h" JNIEXPORT void JNICALL Java_Hello_hello(JNIEnv* env, jobject obj) { printf("Hello, World.\n"); }
6 Rutgers University Excellence Campaign 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); }
Rutgers University Excellence Campaign 2/20/2004 Thank You