Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Material Type: Notes; Class: INTRO TO LOW-LEVEL PROG; Subject: Computer Science; University: University of Maryland; Term: Fall 2005;
Typology: Study notes
1 / 5
CMSC 212 – S05 (lect 26)^1
CMSC 212 – S05 (lect 26)^2
CMSC 212 – S05 (lect 26)^3
Helloworld.java Java Compiler (javac)
gcc with dynamic lib flags
Helloworld.class
Helloworld.h
javah –jni
stdio.h
jni.h Hello.so
Write Java code
java HelloWorld
Hello World!!
Write C code
Helloworld.c
CMSC 212 – S05 (lect 26)^4
CMSC 212 – S05 (lect 26)^5
C Function Signature-Constructing the function name
#include <jni.h> #include "HelloWorld.h" #include <stdio.h>
JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld (JNIEnv *env, jobject obj) { printf("Hello world!\n"); return; }
class HelloWorld { public native void displayHelloWorld();
static { System.loadLibrary("hello"); }
public static void main(String[] args) { new HelloWorld().displayHelloWorld(); } }
CMSC 212 – S05 (lect 26)^6
l Mapping Types
Long Jlong 64
Int Jint 32
Short Jshort 16
Char Jchar 16
Boolean Jboolean 8, unsigned
Byte Jbyte 8
Java Type Native Type Size (bits)
CMSC 212 – S05 (lect 26)^7
jobject
jstring java.lang.String objects jthrowable java.lang.Throwable exceptions
jarray (jintArray, jfloatArray…)
jclass java.lang.Class objects
CMSC 212 – S05 (lect 26)^8
JNIEXPORT jfloat JNICALL Java_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; }
CMSC 212 – S05 (lect 26)^9
JNIEXPORT 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); }
CMSC 212 – S05 (lect 26)^10