120 likes | 251 Views
Advanced Java Session 10. New York University School of Continuing and Professional Studies. Objectives. Java Native Interfaces Overview How to call C/C++ methods from Java. Why JNI. To use a platform-dependent feature that’s not supported by the standard java library
E N D
Advanced JavaSession 10 New York University School of Continuing and Professional Studies
Objectives • Java Native Interfaces • Overview • How to call C/C++ methods from Java
Why JNI • To use a platform-dependent feature that’s not supported by the standard java library • To use a library that’s already been written in C/C++ • To implement some portions that are extremely time-critical in C/C++ for performance reasons
Calling a C function from Java • Generate a C stub for a function that translates between the Java call and C call • Create a special shared library and export the stub • Use a special method – System.loadLibrary – to load the shared library into JVM
HelloNative.java class HelloNative { public native static void greeting(); }
Generate header file • Compile the java class javac HelloNative.java • Use “javah” to generate the header file javah HelloNative JNIEXPORT void JNICALL Java_HelloWorld_greeting (JNIEnv *, jobject);
Running the program • Write the implementation in C that makes the call • Create a shred library with the stub and the actual C code that you want to call • Now you can run the program
Numeric Parameters Java C Bytes boolean jboolean 1 byte jbyte 1 char jchar 2 short jshort 2 int jint 4 long jlong 8 float jfloat 4 double jdouble 8
String Parameters/Returns • Strings in Java use 2-byte character set • JNI provides functions to convert a java String into C/C++ character arrays and vice versa via the JNIEnv pointer jstring jstr; char greeting[] = “Hello World”; jstr = (*env)->NewStringUTF(env, greeting);
String Parameters/Returns • Strings in Java use 2-byte character set • JNI provides functions to convert a java String into C/C++ character arrays and vice versa via the JNIEnv pointer jstring jstr; char greeting[] = “Hello World”; jstr = (*env)->NewStringUTF(env, greeting);
Accessing Object Fields • To get the “double” field called “salary” from a class Employee – jclass class_Employee = (*env)->GetObjectClass(env, obj) jfieldID id_salary = (*env)->GetFieldID( env, class_Employee, “salary”, “D”)