Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University.

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Kernighan/Ritchie: Kelley/Pohl:
Inlining Java Native Calls at Runtime (CASCON 2005 – 4 th Workshop on Compiler Driven Performance) Levon Stepanian, Angela Demke Brown Computer Systems.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
More Specifically JNI Justin Catterson.  ADA  C++  Java  Ruby  Python  Haskell  Perl  etc. What is a Foreign Function Interface? Simply an interface.
Interoperability Kathleen Fisher. Why is interoperability important? Write each part of a complex system in a language well-suited to the task: –C for.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Writing Native Code for Android Systems. Why ndk There exist large c++ code libraries – E.g., Audio and video compression, e.g., Ogg Vorbis, The LAME.
I Dream of JNI When it absolutely, positively has to be written in COBOL... shudder.
Principles of Object-Oriented Software Development The language Java.
Administrivia No class next Monday (May 2) Enjoy extra time on P3. ;-) Reading 3 available “Reflections on Trusting Trust”, Ken Thompson No written summary.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Java Native Interface (JNI). JNI Linking Java and C code.
Lesson 7 Collections, Generics JNI. What is the Collections framework?  Collections framework provides two things: –implementations of common high-level.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Peter Juszczyk CS 492/493 - ISGS. // Is this C# or Java? class TestApp { static void Main() { int counter = 0; counter++; } } The answer is C# - In C#
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
OOP Languages: Java vs C++
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Parallel Programming in Java with Shared Memory Directives.
Programming Languages and Paradigms Object-Oriented Programming.
Java and C++, The Difference An introduction Unit - 00.
Java Programming Robert Chatley William Lee
Java Native Interface CS587x Lecture Department of Computer Science Iowa State University.
What is Android NDK ● A toolset that lets you embed in you app native source code ● C, C++(recently supported December 2010) and assembly(?) ● It is supported.
Chapter 2: Everything is an Object ● C++ has many non object oriented features inherited from C. It is a hybrid language meaning that it support different.
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Java Spring PImage Let’s look at the PImage class in ProcessingPImage –What are the fields (i.e., variables)? –What methods are available? –What.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Rutgers University Excellence Campaign 2/20/2004 Java Native Interface Tutorial Xiaolin Li Rutgers.
Java Introduction to JNI Prepared by Humaira Siddiqui.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Chapter 1: Introducing JAVA. 2 Introduction Why JAVA Applets and Server Side Programming Very rich GUI libraries Portability (machine independence) A.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Lecture :2 1.  DEFENTION : Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed.
POS 406 Java Technology And Beginning Java Code
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Introduction to java Prepared By:-Pragnesh Patel Lect. In Computer Dept. NSIT,Jetalpur 1.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 15: More-Advanced Concepts.
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
National Taiwan University Department of Computer Science and Information Engineering National Taiwan University Department of Computer Science and Information.
Android JNI and JAR Library JNI Library 1. JNI *.c sources file must include jni header file jni.h #include 2. In Make file CFLAGS must add -I $(NDK_INC)/
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
12/8/2015\course\cpeg323-07Fs\Topic2b-323.ppt1 Topic 2b High-Level languages and System Software (Languages) Introduction to Computer Systems Engineering.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Slide Advanced Programming 2004, based on LY Stefanus's slides Native Methods.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
From C++ to Java SNU iDB Lab. Hyoung-woo Park March 26, 2007.
© 2012 Pearson Education, Inc. All rights reserved types of Java programs Application – Stand-alone program (run without a web browser) – Relaxed.
Today… “Hello World” ritual. Brief History of Java & How Java Works. Introduction to Java class structure. But first, next slide shows Java is No. 1 programming.
introductory lecture on java programming
Spring 2009 Programming Fundamentals I Java Programming XuanTung Hoang Lecture No. 8.
C is a high level language (HLL)
ITP 109 Week 2 Trina Gregory Introduction to Java.
Memory Management in Java Mr. Gerb Computer Science 4.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
JNI: Java Native Interface(1/32) Real Time Systems LAB. JNI: Java Native Interface October 31, 2001 Kyung-Yim, Kim.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
Java Native Interface (JNI)
Intro to ETEC Java.
Getting Started ARCS Lab..
The C Language: Intro.
Presentation transcript:

Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University

Introduction What is native method What is Java Native Interface (JNI) Why we use JNI How to use JNI Embedding C in Java Using Java features from C Embedding the VM

What is Native Method Functions written in a language other than Java They could be C, C++, or even assembly

What is JNI Java interface to non-Java code. It is Java's link to the "outside world" Native methods are compiled into a dynamic link library (.dll,.so, etc.) OS loads and links the library into the process that is running the Java Virtual Machine Part of the Java Developer Kit(JDK), serves as a glue between java side and native side of an application Allows Java code that runs inside a Java Virtual Machine (JVM) to interoperate with applications and libraries written in other programming languages, such as C, C++, and assembly

JNI Overview

Why Use JNI Some functionality are not provided by java Low-level drives/devices specific to OS Increase performance by implementing rigorous tasks in native language Java is slow in general and may not be suitable for some functions (e.g., image compression and decompression) Try to use existing legacy library and could not afford to rewrite it in java JNI can be used as a wrapper of these legacy codes Can slowly migrate legacy code to a newer platform Improve efficiency of integration TCP/IP sockets can be used, but there are overhead in data transmission

Justification Pros: Reuse: allows access to useful native code Efficiency: use best language for the task Cons: Portability: native methods aren't portable Extra work: javah, create shared native libs

Interactions with Native Code Access to Java world from native code Access to native code from Java

Using The JNI Java calls C Embedding C in Java C calls Java Using Java features from C Embedding the VM

Embedding C in Java 1. Declare the method using the keyword native, provide no implementation. 2. Make sure the Java loads the needed library 3. Run the javah utility to generate names/headers 4. Implement the method in C 5. Compile as a shared library class HelloWorld { public native void displayHelloWorld(); static { System.loadLibrary("hello"); } public static void main(String[] args) { new HelloWorld().displayHelloWorld(); }

Generate JNI Header Compile HelloWorld.java javac HelloWorld.java Generate HelloWorld.h javah HelloWorld

HelloWorld.h #include “jni.h” /* Header for class HelloWorld */ #ifndef _Included_HelloWorld #define _Included_HelloWorld #ifdef __cplusplus extern “C” { #endif /* * Class: HelloWorld * Method: displayHelloWorld * Signature: ()V */ JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject); #ifdef __cplusplus } #endif The calling object The JVM reference

HelloWorldImp.c #include #include "HelloWorld.h" #include JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj) { printf("Hello world!\n"); return; }

Create a Shared Library class HelloWorld {... System.loadLibrary("hello");... } Compile the native code into a shared library: popeye (Linux) cc -shared -I/usr/java/j2sdk1.4.1_04/include \ -I/usr/java/j2sdk1.4.1_04/include/linux \ HelloWorldImpl.c -o libhello.so -Wl,--add-stdcall-alias In my Windows, it is needed!

Reference --add-stdcall-alias If given, symbols with a stdcall suffix will be exported as-is and also with the suffix stripped. _conventions gling

Run the Program Command: java HelloWorld Result: Hello World! Possible exceptions: java.lang.UnsatisfiedLinkError: no hello in shared library path at java.lang.Runtime.loadLibrary(Runtime.java) at java.lang.System.loadLibrary(System.java) at java.lang.Thread.init(Thread.java) On popeye (Linux), do this: LD_LIBRARY_PATH=./ export LD_LIBRARY_PATH

Primitive Types and Native Equivalents Java TypeNative TypeSize in bits booleanjboolean 8, unsigned bytejbyte 8 charjchar 16, unsigned shortjshort 16 intjint 32 longjlong 64 floatjfloat 32 doublejdouble 64 void n/a Platform-specific implementation Generic interface to programmer Each element of Java language must have a corresponding native counterpart

Object Types and Native Equivalents

Mapping Example class Prompt { private native String getLine(String prompt); } JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *, jobject, jstring); Prefix + fully qualified class name + “_” + method name

Accessing Java Strings /* Illegal */ JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt) { printf("%s", prompt);... } This jstring type is different from the regular C string type /* correct way */ JNIEXPORT jstring JNICALL Java_Prompt_getLine(JNIEnv *env, jobject obj, jstring prompt) { const char *str = (*env)->GetStringUTFChars(env, prompt, 0); printf("%s", str); /* release the memory allocated for the string operation */ (*env)->ReleaseStringUTFChars(env, prompt, str);... } For the functions associated with JNI objects, go to web page:

Accessing Java Array /* Illegal */ JNIEXPORT jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr) { int i, sum = 0; for (i=0; i<10; i++) { sum += arr[i]; }... /* correct way */ JNIEXPORT jint JNICALL Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr) { int i, sum = 0; /* 1. obstain the length of the array */ jsize len = (*env)->GetArrayLength(env, arr); /* 2. obtain a pointer to the elements of the array */ jint *body = (*env)->GetIntArrayElements(env, arr, 0); /* 3. operate on each individual primitive or jobjects */ for (i=0; i<len; i++) { sum += body[i]; } /* 4. release the memory allocated for array */ (*env)->ReleaseIntArrayElements(env, arr, body, 0);

Accessing Java Member Variables fid = (*env)->GetStaticFieldID(env, cls, "si", "I"); /* 1. get the field ID */ si = (*env)->GetStaticIntField(env, cls, fid); /* 2. find the field variable */ (*env)->SetStaticIntField(env, cls, fid, 200); /* 3. perform operation on the primitive*/ fid = (*env)->GetFieldID(env, cls, "s", "Ljava/lang/String;"); /* 1. get the field ID */ jstr = (*env)->GetObjectField(env, obj, fid); /* 2. find the field variable */ jstr = (*env)->NewStringUTF(env, "123"); /* 3. perform operation on the object */ (*env)->SetObjectField(env, obj, fid, jstr); class FieldAccess { static int si; /* signature is “si” */ String s; /* signature is “ Ljava/lang/String;"; } /* run javap -s -p FieldAccess to get the signature */

Calling a Java Method 1. Find the class of the object Call GetObjectClass 2. Find the method ID of the object Call GetMethodID, which performs a lookup for the Java method in a given class 3. Call the method JNI provides an API for each type of method e.g., CallVoidMethod(), etc. You pass the object, method ID, and the actual arguments to the method (e.g., CallVoidMethod) Example of Call: jclass cls = (*env)->GetObjectClass(env, obj); jmethodID mid = (*env)->GetMethodID(env, cls, “hello”, “(I)V”); (*env)->CallVoidMethod(env, obj, mid, parm1);

Garbage Collection Issues Only Arrays and explicitly globally created objects are “pinned” down and must be explicitly released Everything else is released upon the native method returning

Thread Issues The JNI interface pointer (JNIEnv *) is only valid in the current thread You must not pass the interface pointer from one thread to another You must not pass local references from one thread to another Check the use of global variables carefully (locking is needed)

Synchronization Synchronize is available as a C call Wait and Notify calls through JNIEnv do work and are safe to use Could use native threading operations for native to native threading, but this may cost portability In java: synchronized (obj) {... /* synchronized block */... } In C: (*env)->MonitorEnter(env, obj); /* synchronized block */ (*env)->MonitorExit(env, obj);

Embedding a VM in C Just a special kind of Java Call from C (see reference) You get a pointer into your resulting environment and by the VM are treated as a native method With the exception you never “return” so it is your responsibility to do everything globally

References