Docsity

Notes on Java Native Interface - Project #4 | CMSC 212, Study Guides, Projects, Research of Computer Science

Partial preview of the text

Download Notes on Java Native Interface - Project #4 | CMSC 212 and more Study Guides, Projects, Research Computer Science in PDF only on Docsity!

Announcements

l^ Program #5– is due Thursday l^ Reading– http://java.sun.com/docs/books/tutorial/native1.1/ l^ Pickup old assignments with project #4– Midterms (including re-grades)– Programming assignments

Java Native Interface

l^ Goals (both directions)– Sometimes need to access things in lower level language– Provide full access to Java Objects in other languages l^ Keys Ideas– Need to identify signatures of native methods– Need to incorporate native code into program

Using JNI Functions

l^ Declaring Functions in Java– (where the function to be used is written in C)– Declare like a normal method, but add “native” keyword– public native void displayHelloWorld(); l^ Loading the Code– Use loadLibrary call– Making it static forces it to happened automatically– System.loadLibrary("hello")– Java’s equivalent of

dlopen

– adds the appropriate name completion for this system l Invoke Native Method– new HelloWorld().displayHelloWorld();– this invokes the C code

C Function Signature-Constructing the function nameCMSC 212 – S05 (lect 26)

-^ Java_ + Full Classname + _ + Method NameJNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld (JNIEnv *, jobject);

#include <jni.h>#include "HelloWorld.h"#include <stdio.h>JNIEXPORT void JNICALLJava_HelloWorld_displayHelloWorld

(JNIEnv *env, jobject obj) { printf("Hello world!\n");return;}

class HelloWorld {public nativevoid displayHelloWorld();static {System.loadLibrary("hello");} public static void main(String[] args){ newHelloWorld().displayHelloWorld();} }

Access Java Arrays

l^ Need to call special functions to get data and size l^ Example:JNIEXPORT jfloat JNICALLJava_FloatArray_sumArray(JNIEnv env, jobject obj, jfloatArray arr) {jfloat body, sum = 0;jsize I, len;len = (env)->GetArrayLength(env, arr);body = (env)->GetFloatArrayElements(env, arr, 0);for (i=0; i<len; i++) {

sum += body[i];} (*env)->ReleaseFloatArrayElements(env, arr, body, 0);return sum;}

Calling Java Methods from C

l^ Steps– Get Object handle– Get MethodID – need to know signature• (argument-types)return-type– Call method l^ ExampleJNIEXPORT void JNICALL Java_Callbacks_nativeMethod(JNIEnv env, jobject obj, jint depth) {jclass cls = (env)->GetObjectClass(env, obj);jmethodID mid = (env)->GetMethodID(env, cls, "callback", "(I)V");if (mid == 0) { return; }printf("In C, depth = %d, about to enter Java\n", depth);(env)->CallVoidMethod(env, obj, mid, depth);printf("In C, depth = %d, back from Java\n", depth);}