NDK Integration (JNI)

Similar documents
VOL. 3, NO.10 Oct, 2012 ISSN Journal of Emerging Trends in Computing and Information Sciences CIS Journal. All rights reserved.

Numerical Algorithms Group

Programming CAN-based Fieldbus Systems using Java

Java/C++ integration: Writing native Java methods in natural C++

Introduction to Native Android Development with NDK

Crash Course in Java

Wrapper Generator using Java Native Interface

Java Interview Questions and Answers

Java Crash Course Part I

CS Software Engineering for Scientific Computing. Lecture 25:Mixed Language Programming.

Multithreading and Java Native Interface (JNI)!

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Introduction to Java

Development_Setting. Step I: Create an Android Project

Reach 4 million Unity developers

AAC-ELD based Audio Communication on Android

An Overview of Java. overview-1

Pemrograman Dasar. Basic Elements Of Java

Chapter 1 Java Program Design and Development

Java Programming Fundamentals

Sources: On the Web: Slides will be available on:

Native code in Android Quad Detection

The Decaffeinated Robot

CS 106 Introduction to Computer Science I

Extending your Qt Android application using JNI

Java from a C perspective. Plan

public static void main(string[] args) { System.out.println("hello, world"); } }

The C Programming Language course syllabus associate level

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

JNI Java Native Interface. C and C++ Justification. Embedding C in Java. Generate JNI Header. HelloWorld.h

CSE 452: Programming Languages. Acknowledgements. Contents. Java and its Evolution

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Lecture 5: Java Fundamentals III

Android NDK Native Development Kit

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

CSC230 Getting Starting in C. Tyler Bletsch

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Using the Java Native Interface to Introduce Device Driver Basics

JVM Tool Interface. Michal Pokorný

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

How To Write Portable Programs In C

The Java Virtual Machine and Mobile Devices. John Buford, Ph.D. Oct 2003 Presented to Gordon College CS 311

RTI Connext DDS. Core Libraries Getting Started Guide Addendum for Android Systems Version 5.2.0

CS506 Web Design and Development Solved Online Quiz No. 01

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

University of Twente. A simulation of the Java Virtual Machine using graph grammars

An Empirical Security Study of the Native Code in the JDK

Java programming for C/C++ developers

Java Virtual Machine, JVM

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Fachbereich Informatik und Elektrotechnik SunSPOT. Ubiquitous Computing. Ubiquitous Computing, Helmut Dispert

Using EDA Databases: Milkyway & OpenAccess

COSC282 BIG DATA ANALYTICS FALL 2015 LECTURE 2 - SEP 9

Contents. Java - An Introduction. Java Milestones. Java and its Evolution

To Java SE 8, and Beyond (Plan B)

Lecture 1 Introduction to Android

Informatica e Sistemi in Tempo Reale

Contents at a Glance

Android Hands-On Labs

Comp151. Definitions & Declarations

The programming language C. sws1 1

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Object Oriented Software Design II

CSC 551: Web Programming. Fall 2001

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

C++ Programming Language

Android Malware for Pen-testing. IOAsis San Fransicso 2014

What is Java? Applications and Applets: Result of Sun s efforts to remedy bad software engineering practices

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

02 B The Java Virtual Machine

Tutorial: Getting Started

OpenCV on Android Platforms

Lecture 17: Mobile Computing Platforms: Android. Mythili Vutukuru CS 653 Spring 2014 March 24, Monday

Mobile application development J2ME U N I T I I

CSC 551: Web Programming. Spring 2004

A Short Introduction to Writing Java Code. Zoltán Majó

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

picojava TM : A Hardware Implementation of the Java Virtual Machine

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

WRITING DATA TO A BINARY FILE

Cloud Computing. Up until now

5 Arrays and Pointers

Introduction to Object-Oriented Programming

Java applets. SwIG Jing He

Restraining Execution Environments

IBM SDK, Java Technology Edition Version 1. IBM JVM messages IBM

Install Java Development Kit (JDK) 1.8

1 The Java Virtual Machine

Application-only Call Graph Construction

An Incomplete C++ Primer. University of Wyoming MA 5310

Number Representation

A Java Virtual Machine Architecture for Very Small Devices

Fundamentals of Java Programming

RTI Monitoring Library Getting Started Guide

Rootbeer: Seamlessly using GPUs from Java

Installing Java. Table of contents

Transcription:

NDK Integration (JNI) Lecture 5 Android Native Development Kit 25 March 2014 NDK NDK Integration (JNI), Lecture 5 1/34

Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 2/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 3/34

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) NDK NDK Integration (JNI), Lecture 5 4/34

Standard JNI Two-way interface Allows Java apps to invoke native code and vice versa NDK NDK Integration (JNI), Lecture 5 5/34

Two-way Interface 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 NDK NDK Integration (JNI), Lecture 5 6/34

Implications of Using JNI Java apps are portable Runs 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 NDK NDK Integration (JNI), Lecture 5 7/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 8/34

Hello World Example 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 NDK NDK Integration (JNI), Lecture 5 9/34

Hello World Example c l a s s HelloWorld { s t a t i c { System. l o a d L i b r a r y ( HelloWorld ) ; } p r i v a t e native void p r i n t ( ) ; p u b l i c s t a t i c void main ( S t r i n g [ ] a r g s ) { new HelloWorld ( ). p r i n t ( ) ; } } 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 NDK NDK Integration (JNI), Lecture 5 10/34

Hello World Example 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); NDK NDK Integration (JNI), Lecture 5 11/34

Hello World Example #i n c l u d e < j n i. h> #i n c l u d e <s t d i o. h> #i n c l u d e HelloWorld. h JNIEXPORT void JNICALL J a v a H e l l o W o r l d p r i n t ( JNIEnv env, j o b j e c t o b j ) { p r i n t f ( H e l l o World! \ n ) ; return ; } Follow the prototype in the generated header file jni.h - needed for native code to call JNI functions NDK NDK Integration (JNI), Lecture 5 12/34

Hello World Example 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 NDK NDK Integration (JNI), Lecture 5 13/34

Hello World Example 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 NDK NDK Integration (JNI), Lecture 5 14/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 15/34

JNIEnv interface pointer 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 NDK NDK Integration (JNI), Lecture 5 16/34

JNIEnv interface pointer 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 a C++ class JNI functions exposed as member functions JNI functions have access to the current JNI environment e.g. return env->newstringutf("hello!"); NDK NDK Integration (JNI), Lecture 5 17/34

Second Argument 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 NDK NDK Integration (JNI), Lecture 5 18/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 19/34

Mapping of Types 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) NDK NDK Integration (JNI), Lecture 5 20/34

Primitive Types Java Type JNI Type C/C++ Type Size boolean jboolean unsigned char unsigned 8 bits byte jbyte char signed 8 bits char jchar unsigned short unsigned 16 bits short jshort short signed 16 bits int jint int signed 32 bits long jlong long long signed 64 bits float jfloat float 32 bits double jdouble double 64 bits NDK NDK Integration (JNI), Lecture 5 21/34

Objects 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. NDK NDK Integration (JNI), Lecture 5 22/34

Reference Types Java Type java.lang.class java.lang. String java.lang.throwable other objects java.lang.object[] boolean[] byte[] char[] short[] int[] long[] float[] double[] other arrays Native Type jclass jstring jthrowable jobject jobjectarray jbooleanarray jbytearray jchararray jshortarray jintarray jlongarray jfloatarray jdoublearray jarray NDK NDK Integration (JNI), Lecture 5 23/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 24/34

String Types 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 NDK NDK Integration (JNI), Lecture 5 25/34

Convert C String to Java String NewStringUTF, NewString jstring javastring = (*env)->newstringutf(env, "Hello!"); 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 NDK NDK Integration (JNI), Lecture 5 26/34

GetStringUTFChars, GetStringChars Convert Java String to C String const jbyte* str = (*env)->getstringutfchars(env, javastring, &iscopy); const jchar* str = (*env)->getstringchars(env, javastring, &iscopy); 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 NDK NDK Integration (JNI), Lecture 5 27/34

Release Strings Free memory occupied by the C string ReleaseStringUTFChars, ReleaseStringChars (*env)->releasestringutfchars(env, javastring, str); String should be released after it is used Avoid memory leaks Frees the copy or unpins the instance (copy or not) NDK NDK Integration (JNI), Lecture 5 28/34

Length and Copy in Buffer Get string length GetStringUTFLength/GetStringLength on the jstring Or strlen on the GetStringUTFChars result Copy string elements into a preallocated buffer (*env)->getstringutfregion(env, javastring, 0, len, buffer); start index and length length can be obtained with GetStringLength buffer is char[] No memory allocation, no out-of-memory checks NDK NDK Integration (JNI), Lecture 5 29/34

Critical Region 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 NDK NDK Integration (JNI), Lecture 5 30/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 31/34

Bibliography http://www.soi.city.ac.uk/~kloukin/in2p3/ material/jni.pdf http://docs.oracle.com/javase/6/docs/technotes/ guides/jni/spec/jnitoc.html http://download.java.net/jdk8/docs/technotes/ guides/jni/spec/functions.html http://developer.android.com/training/articles/ perf-jni.html Onur Cinar, Pro Android C++ with the NDK, Chapter 3 Sylvain Ratabouil, Android NDK, Beginner s Guide, Chapter 3 NDK NDK Integration (JNI), Lecture 5 32/34

Outline Standard JNI Standard JNI Example Native Method Arguments Mapping of Types Operations on Strings Bibliography Keywords NDK NDK Integration (JNI), Lecture 5 33/34

Jave 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 To be continued.. NDK NDK Integration (JNI), Lecture 5 34/34