This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
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.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
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.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
Java Native Interface Modified from CS587x Lecture Department of Computer Science Iowa State University.
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
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.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Administrivia No class next Monday (May 2) Enjoy extra time on P3. ;-) Reading 3 available “Reflections on Trusting Trust”, Ken Thompson No written summary.
Java Native Interface (JNI). JNI Linking Java and C code.
Netprog 2002 Java Intro1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network.
A Short Introduction to JAVA
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
Platforms and tools for Web Services and Mobile Applications Introduction to C# Bent Thomsen Aalborg University 3rd and 4th of June 2004.
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit
OOP Languages: Java vs C++
CSC3170 Introduction to Database Systems
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Programming Languages and Paradigms Object-Oriented Programming.
Java and C++, The Difference An introduction Unit - 00.
Java Native Interface CS587x Lecture Department of Computer Science Iowa State University.
EECE 310: Software Engineering Lecture 2: Understanding Objects in Java and Types.
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.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
Java Introduction Lecture 1. Java Powerful, object-oriented language Free SDK and many resources at
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
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.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
Jaeki Song ISQS6337 JAVA Lecture 03 Introduction to Java -The First Java Application-
Lecture :2 1.  DEFENTION : Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed.
2: Everything is an Object You Manipulate Objects Using References Primitives Arrays in Java Scoping You Never Destroy Objects Creating New Data Types:
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.
Java for C++ Programmers Clint Jeffery University of Idaho
1 Introduction to Java. 2 What is Java? A programming language. A platform –A virtual machine (JVM) definition. –Runtime environments in diverse hardware.
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)/
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
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.
Slide Advanced Programming 2004, based on LY Stefanus's slides Native Methods.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
RealTimeSystems Lab Jong-Koo, Lim
Object Oriented Programming Lecture 2: BallWorld.
Spring 2006 Special Topics in Computer Engineering: Java Intro 1 Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J.
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.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
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.
EECE 309: Software Engineering
Computer Organization and Design Pointers, Arrays and Strings in C
Java Programming Language
CompSci 230 Software Construction
Java Basics Data Types in Java.
SPL – PS3 C++ Classes.
Presentation transcript:

This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. Lecture 5 - NDK Integration (JNI)

Laura Gheorghe, Petre Eftime Standard JNI  Java Native Interface (JNI)  Native Programming Interface  Allows Java code to interoperate with apps and libraries written in other programming languages  When do we use JNI?  Java library does not support platform-dependent features  Use already existent library written in other language  Time-critical code in a low level language (performance) 2

Laura Gheorghe, Petre Eftime Standard JNI 3  Two-way interface  Allows Java apps to invoke native code and vice versa

Laura Gheorghe, Petre Eftime Two-way Interface 4  Support for two types of native code  Native libraries  Call functions from native libraries  In the same way they call Java methods  Native applications  Embed a Java VM implementation into native apps  Execute components written in Java  e.g. C web browser executes applets in an embedded Java VM implementation

Laura Gheorghe, Petre Eftime Implications of Using JNI 5  Java apps are portable  Run on multiple platforms  The native component will not run on multiple platforms  Recompile the native code for the new platform  Java is type-safe and secure  C/C++ are not  Misbehaving native code can affect the whole application  Security checks when invoking native code  Extra care when writing apps that use JNI  Native methods in few classes  Clean isolation between native code and Java app

Laura Gheorghe, Petre Eftime Hello World Example 6  Simple Java app calling a C function to print ”Hello World” 1. Create HelloWorld.java that declares the native method 2. Compile HelloWorld.java using javac => HelloWorld.class 3. Use javah -jni to create C header file (function prototype) => HelloWorld.h 4. Write C implementation on native method => HelloWorld.c 5. Compile C code into native library => libHelloWorld.so / HelloWorld.dll 6. Run HelloWorld using java runtime interpreter  The class and native library loaded at runtime

Laura Gheorghe, Petre Eftime Hello World Example 7  In the static initializer we load the native library  The native library on disk is called libHelloWorld.so or HelloWorld.dll  Declare the print native method ( native modifier)  In main we instantiate the HelloWorld class and invoke print native method class HelloWorld { static { System.loadLibrary("HelloWorld"); } private native void print(); public static void main(String[] args) { new HelloWorld().print(); }

Laura Gheorghe, Petre Eftime Hello World Example 8  Compile the Java source code  javac HelloWorld.java  Creates HelloWorld.class in the same directory  Generate JNI-style header file using javah tool  javah -jni HelloWorld  Generates HelloWorld.h  Includes prototype for Java_HelloWorld_print  JNIEXPORT void JNICALL Java_HelloWorld_print (JNIEnv *, jobject);

Laura Gheorghe, Petre Eftime Hello World Example 9  Follow the prototype in the generated header file  jni.h - needed for native code to call JNI functions #include #include "HelloWorld.h" JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj) { printf("Hello World!\n"); return; }

Laura Gheorghe, Petre Eftime Hello World Example 10  Compile C code and build native library  Linux:  gcc -I/java/include -I/java/include/linux -shared -o libHelloWorld.so HelloWorld.c  Windows:  cl -IC:\java\include -IC:\java\include\win32 -MD -LD HelloWorld.c -FeHelloWorld.dll

Laura Gheorghe, Petre Eftime Hello World Example 11  Run java app  java HelloWorld  Before, set the native library path to the current directory  java.lang.UnsatisfiedLinkError: no HelloWorld in library path at java.lang.Runtime.loadLibrary(Runtime.java) at java.lang.System.loadLibrary(System.java) at HelloWorld.main(HelloWorld.java)  Linux: LD_LIBRARY_PATH=. export LD_LIBRARY_PATH  Windows: library in the current dir or in a dir from PATH  Or specify the native library path when running java  java -Djava.library.path=. HelloWorld

Laura Gheorghe, Petre Eftime JNIEnv interface pointer 12  Passed into each native method call as the first argument  Valid only in the current thread (cannot be used by other threads)  Points to a location that contains a pointer to a function table  Each entry in the table points to a JNI function  Native methods access data structures in the Java VM through JNI functions

Laura Gheorghe, Petre Eftime JNIEnv interface pointer 13  For C and C++ source files the syntax for calling JNI functions differs  C code  JNIEnv is a pointer to a JNINativeInterface structure  Pointer needs to be dereferenced first  JNI functions do not know the current JNI environment  JNIEnv instance should be passed as the first argument to the function call  e.g. return (*env)->NewStringUTF(env, "Hello!");  C++ code  JNIEnv is a C++ class  JNI functions exposed as member functions  JNI functions have access to the current JNI environment  e.g. return env->NewStringUTF("Hello!");

Laura Gheorghe, Petre Eftime Second Argument 14  Second argument depends whether the method is static or instance  Instance methods - can be called only on a class instance  Static methods - can be called directly from a static context  Both can be declared as native  For instance native method  Reference to the object on which the method is invoked (this in C++)  e.g. jobject thisObject  For static native method  Reference to the class in which the method is defined  e.g. jclass thisClass

Laura Gheorghe, Petre Eftime Mapping of Types 15  JNI defines a set of C/C++ types corresponding to Java types  Java types  Primitive types: int, float, char  Reference types: classes, instances, arrays  The two types are treated differently by JNI  int -> jint (32 bit integer)  float -> jfloat (32 bit floating point number)

Laura Gheorghe, Petre Eftime Primitive Types 16 Java TypeJNI TypeC/C++ TypeSize booleanjbooleanunsigned charunsigned 8 bits bytejbytecharsigned 8 bits charjcharunsigned shortunsigned 16 bits shortjshortshortsigned 16 bits intjintintsigned 32 bits longjlonglong signed 64 bits floatjfloatfloat32 bits doublejdoubledouble64 bits

Laura Gheorghe, Petre Eftime Objects 17  Objects -> opaque references  C pointer to internal data structures in the Java VM  Objects accessed using JNI functions (JNIEnv interface pointer)  e.g. GetStringUTFChars() function for accessing the contents of a string  All JNI references have type jobject  All reference types are subtypes of jobject  Correspond to the most used types in Java  jstring, jobjectArray, etc.

Laura Gheorghe, Petre Eftime Reference Types 18 Java TypeNative Type java.lang.Classjclass java.lang. Stringjstring java.lang.Throwablejtrowable other objectsjobject java.lang.Object[]jobjectArray boolean[]jbooleanArray byte[]jbyteArray char[]jcharArray short[]jshortArray int[]jintArray long[]jlongArray float[]jfloatArray double[]jdoubleArray other arraysjarray

Laura Gheorghe, Petre Eftime String Types 19  String is a reference type in JNI ( jstring )  Cannot be used directly as native C strings  Need to convert the Java string references into C strings and back  No function to modify the contents of a Java string (immutable objects)  JNI supports UTF-8 and UTF-16/Unicode encoded strings  UTF-8 compatible with 7-bit ASCII  UTF-8 strings terminated with ’\0’ char  UTF-16/Unicode - 16 bits, not zero-terminated  Two sets of functions  jstring is represented in Unicode in the VM

Laura Gheorghe, Petre Eftime Convert C String to Java String 20  NewStringUTF, NewString  Takes a C string, returns a Java string reference type  If the VM cannot allocate memory  Returns NULL  OutOfMemoryError exception thrown in the VM  Native code should not continue jstring javaString = env->NewStringUTF("Hello!");

Laura Gheorghe, Petre Eftime Convert Java String to C String 21  GetStringUTFChars, GetStringChars  isCopy  JNI_TRUE - returned string is a copy of the chars in the original instance  JNI_FALSE - returned string is a direct pointer to the original instance (pinned object in heap)  Pass NULL if it’s not important  If the string contains only 7-bit ASCII chars you can use printf  If the memory allocation fails it returns NULL, throws OutOfMemory exception const jbyte* str = env->GetStringUTFChars(javaString, &isCopy); const jchar* str = env->GetStringChars(javaString, &isCopy);

Laura Gheorghe, Petre Eftime Release Strings 22  Free memory occupied by the C string  ReleaseStringUTFChars, ReleaseStringChars  String should be released after it is used  Avoid memory leaks  Frees the copy or unpins the instance (copy or not) env->ReleaseStringUTFChars(javaString, str);

Laura Gheorghe, Petre Eftime Length and Copy in Buffer 23  Get string length  GetStringUTFLength/GetStringLength on the jstring  Or strlen on the GetStringUTFChars result  Copy string elements into a preallocated buffer  start index and length  length can be obtained with GetStringLength  buffer is char[]  No memory allocation, no out-of-memory checks env->GetStringUTFRegion(javaString, 0, len, buffer);

Laura Gheorghe, Petre Eftime Critical Region 24  GetStringCritical, ReleaseStringCritical  Increase the probability to obtain a direct pointer to the string  Critical Section between the calls  Must not make blocking operations  Must not allocate new objects in the Java VM  Disable garbage collection when holding a direct pointer to a string  Blocking operations or allocating objects may lead to deadlock  No GetStringUTFCritical -> usually makes a copy of the string

Laura Gheorghe, Petre Eftime Bibliography 25  f  ni/spec/jniTOC.html  /spec/functions.html  jni.html  Onur Cinar, Pro Android C++ with the NDK, Chapter 3  Sylvain Ratabouil, Android NDK, Beginner’s Guide, Chapter 3

Laura Gheorghe, Petre Eftime Keywords 26  Java Native Interface  Two-way interface  Native methods  Interface pointer  Static methods  Instance methods  Primitive types  Reference types  JNI functions  Opaque reference  Java string reference  Conversion operations