Lecture Slides on Java Native Interface, JNI Function | CMSC 212, Study notes of Computer Science

Material Type: Notes; Class: INTRO TO LOW-LEVEL PROG; Subject: Computer Science; University: University of Maryland; Term: Spring 2007;

Typology: Study notes

Pre 2010

Uploaded on 07/30/2009

koofers-user-cst
koofers-user-cst 🇺🇸

9 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CMSC 212 – S07 (lect 24)
Announcements
zProgram #5
is due today
zProgram #6
Is on the web
zReading
Today – Notes
Tuesday - Notes
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Lecture Slides on Java Native Interface, JNI Function | CMSC 212 and more Study notes Computer Science in PDF only on Docsity!

Announcements

z^ Program #5– is due today z^ Program #6– Is on the web z^ Reading– Today – Notes– Tuesday - Notes

Java Native Interface

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

Process of Compiling Using JNI

Java Compiler (javac) Helloworld.java

Helloworld.class Helloworld.hgcc HelloworldC.c

Javah –jni

jni.h stdio.h Hello.so

Using JNI Functions

z^ Declaring Functions– Declare like a normal method, but add “native” keyword– public native void displayHelloWorld(); z^ Loading the Code– Use loadLibrary call– Making it static forces it to happened automatically– System.loadLibrary("hello") z^ Invoke Native Method– new HelloWorld().displayHelloWorld();

C Code for JNI Call

#include <jni.h>#include "HelloWorld.h"#include <stdio.h>JNIEXPORT void JNICALLJava_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj){ printf("Hello world!\n");return;}

Accessing Java Data from C

z^ Mapping Types

Jlong Long

Jint Int

Jshort Short

Jchar Char

8, unsigned

Jboolean Boolean

Jbyte Byte

Native Type

Size (bits)

Java Type

Access Java Arrays

z^ Need to call special functions to get data and size z^ 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

z^ Steps– Get Object handle– Get MethodID – need to know signature• (argument-types)return-type– Call method z^ 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);}