ndk integration (jni) · android ndk i android native development kit i allows the embed c/c++...

31
NDK Integration (JNI) Lecture 6 Operating Systems Practical 9 November 2016 This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/. OSP NDK Integration (JNI), Lecture 6 1/31

Upload: others

Post on 11-Jul-2020

21 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

NDK Integration (JNI)Lecture 6

Operating Systems Practical

9 November 2016

This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of thislicense, visit http://creativecommons.org/licenses/by/4.0/.

OSP NDK Integration (JNI), Lecture 6 1/31

Page 2: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

JNI

Android JNI Example

Native Method Arguments

Mapping of Types

Operations on Strings

OSP NDK Integration (JNI), Lecture 6 2/31

Page 3: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Outline

JNI

Android JNI Example

Native Method Arguments

Mapping of Types

Operations on Strings

OSP NDK Integration (JNI), Lecture 6 3/31

Page 4: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

JNI

I Java Native Interface (JNI)

I Native Programming Interface

I Allows Java code to interoperate with apps and librarieswritten in other programming languages

I When do we use JNI?I Java library does not support platform-dependent featuresI Use already existent library written in other languageI Time-critical code in a low level language (performance)

OSP NDK Integration (JNI), Lecture 6 4/31

Page 5: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

JNI

I Two-way interface

I Allows Java apps to invoke native code and vice versa

OSP NDK Integration (JNI), Lecture 6 5/31

Page 6: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Two-way Interface

I Support for two types of native codeI Native libraries

I Call functions from native librariesI In the same way they call Java methods

I Native applicationsI Embed a Java VM implementation into native appsI Execute components written in JavaI e.g. C web browser executes applets in an embedded Java VM

implementation

OSP NDK Integration (JNI), Lecture 6 6/31

Page 7: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Implications of Using JNI

I Java apps are portableI Run on multiple platformsI The native component will not run on multiple platformsI Recompile the native code for the new platform

I Java is type-safe and secureI C/C++ are notI Misbehaving native code can affect the whole applicationI Security checks when invoking native codeI Extra care when writing apps that use JNI

I Native methods in few classesI Clean isolation between native code and Java app

OSP NDK Integration (JNI), Lecture 6 7/31

Page 8: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Android NDK

I Android Native Development KitI Allows the embed C/C++ (native) code in Android

applicationsI Implement your own native code or use existing native libraries

I ndk-buildI Shell script that invokes the NDK build scriptsI Probe the development system and app project file to decide

what to buildI Generate binariesI Copy binaries in the app’s project path

OSP NDK Integration (JNI), Lecture 6 8/31

Page 9: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Outline

JNI

Android JNI Example

Native Method Arguments

Mapping of Types

Operations on Strings

OSP NDK Integration (JNI), Lecture 6 9/31

Page 10: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Basic JNI Example - Android.mk

I Android.mkI Configuration fileI In /jniI The name of the native source file: hello-jni.cI The name of the shared library to build: hello-jniI Built library: libhello-jni.so

LOCAL PATH := $ ( c a l l my−d i r )

i n c l u d e $ (CLEAR VARS)

LOCAL MODULE := h e l l o− j n iLOCAL SRC FILES := h e l l o− j n i . c

i n c l u d e $ ( BUILD SHARED LIBRARY )

OSP NDK Integration (JNI), Lecture 6 10/31

Page 11: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Basic JNI Example - Application.mk

I Application.mkI In /jniI Specifies the CPU and architecture for buildingI In this example - all supported architectures

APP ABI := a l l

OSP NDK Integration (JNI), Lecture 6 11/31

Page 12: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Basic JNI Example - Java code

I Java source code in /srcI Load native library in a static initializerI Declare the native function (native keyword)I Call the native function

package com . example . h e l l o j n i ;

pub l i c c l a s s He l l o J n i extends A c t i v i t y{

@Over r idepub l i c vo id onCreate ( Bundle s a v e d I n s t a n c e S t a t e ){

super . onCreate ( s a v e d I n s t a n c e S t a t e ) ;TextView tv = new TextView ( t h i s ) ;t v . s e tTex t ( s t r i ngFromJNI ( ) ) ;s e tContentV iew ( tv ) ;

}pub l i c n a t i v e S t r i n g s t r i ngFromJNI ( ) ;s t a t i c {

System . l o a d L i b r a r y ( ” h e l l o− j n i ” ) ;}

}

OSP NDK Integration (JNI), Lecture 6 12/31

Page 13: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Basic JNI Example - Native code

I C source code in /jniI Implements the native functionI Includes jni.hI Function name - based on the Java function name and the

path to the file containing itI Arguments:

I JNIEnv * - pointer to the VM, called interface pointerI jobject - implicit this object passed from the Java side

I Creates a string by using a JNI function (NewStringUTF)

#inc l u d e < s t r i n g . h>#inc l u d e < j n i . h>

j s t r i n gJ a v a c om e x amp l e h e l l o j n i H e l l o J n i s t r i n g F r omJN I ( JNIEnv∗ env ,

j o b j e c t t h i z ){

r e t u r n (∗ env)−>NewStringUTF ( env , ” He l l o from JNI” ) ;}

OSP NDK Integration (JNI), Lecture 6 13/31

Page 14: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Outline

JNI

Android JNI Example

Native Method Arguments

Mapping of Types

Operations on Strings

OSP NDK Integration (JNI), Lecture 6 14/31

Page 15: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

JNIEnv interface pointer

I Passed into each native method call as the first argument

I Valid only in the current thread (cannot be used by otherthreads)

I Points to a location that contains a pointer to a function table

I Each entry in the table points to a JNI function

I Native methods access data structures in the Java VMthrough JNI functions

OSP NDK Integration (JNI), Lecture 6 15/31

Page 16: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

JNIEnv interface pointer

I For C and C++ source files the syntax for calling JNIfunctions differs

I C codeI JNIEnv is a pointer to a JNINativeInterface structureI Pointer needs to be dereferenced firstI JNI functions do not know the current JNI environment

I JNIEnv instance should be passed as the first argument to thefunction call

I e.g. return (*env)->NewStringUTF(env, "Hello!");

I C++ codeI JNIEnv is a C++ classI JNI functions exposed as member functionsI JNI functions have access to the current JNI environmentI e.g. return env->NewStringUTF("Hello!");

OSP NDK Integration (JNI), Lecture 6 16/31

Page 17: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Second Argument

I Second argument depends whether the method is static orinstance

I Instance methods - can be called only on a class instance

I Static methods - can be called directly from a static context

I Both can be declared as nativeI For instance native method

I Reference to the object on which the method is invoked (thisin C++)

I e.g. jobject thisObject

I For static native methodI Reference to the class in which the method is definedI e.g. jclass thisClass

OSP NDK Integration (JNI), Lecture 6 17/31

Page 18: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Outline

JNI

Android JNI Example

Native Method Arguments

Mapping of Types

Operations on Strings

OSP NDK Integration (JNI), Lecture 6 18/31

Page 19: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Mapping of Types

I JNI defines a set of C/C++ types corresponding to Java typesI Java types

I Primitive types: int, float, charI Reference types: classes, instances, arrays

I The two types are treated differently by JNI

I int -> jint (32 bit integer)

I float -> jfloat (32 bit floating point number)

OSP NDK Integration (JNI), Lecture 6 19/31

Page 20: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Primitive Types

Java Type JNI Type C/C++ Type Sizeboolean jboolean unsigned char unsigned 8 bitsbyte jbyte char signed 8 bitschar jchar unsigned short unsigned 16 bitsshort jshort short signed 16 bitsint jint int signed 32 bitslong jlong long long signed 64 bitsfloat jfloat float 32 bitsdouble jdouble double 64 bits

OSP NDK Integration (JNI), Lecture 6 20/31

Page 21: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Objects

I Objects -> opaque references

I C pointer to internal data structures in the Java VMI Objects accessed using JNI functions (JNIEnv interface

pointer)I e.g. GetStringUTFChars() function for accessing the

contents of a string

I All JNI references have type jobjectI All reference types are subtypes of jobjectI Correspond to the most used types in JavaI jstring, jobjectArray, etc.

OSP NDK Integration (JNI), Lecture 6 21/31

Page 22: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Reference Types

Java Type Native Typejava.lang.Class jclassjava.lang. String jstringjava.lang.Throwable jthrowableother objects jobjectjava.lang.Object[] jobjectArrayboolean[] jbooleanArraybyte[] jbyteArraychar[] jcharArrayshort[] jshortArrayint[] jintArraylong[] jlongArrayfloat[] jfloatArraydouble[] jdoubleArrayother arrays jarray

OSP NDK Integration (JNI), Lecture 6 22/31

Page 23: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Outline

JNI

Android JNI Example

Native Method Arguments

Mapping of Types

Operations on Strings

OSP NDK Integration (JNI), Lecture 6 23/31

Page 24: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

String Types

I String is a reference type in JNI (jstring)I Cannot be used directly as native C strings

I Need to convert the Java string references into C strings andback

I No function to modify the contents of a Java string(immutable objects)

I JNI supports UTF-8 and UTF-16/Unicode encoded stringsI UTF-8 compatible with 7-bit ASCIII UTF-8 strings terminated with ’\0’ charI UTF-16/UnicodeI Two sets of functionsI jstring is represented in Unicode in the VM

OSP NDK Integration (JNI), Lecture 6 24/31

Page 25: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Convert C String to Java String

I NewStringUTF, NewString

jstring javaString = env->NewStringUTF("Hello!");

I Takes a C string, returns a Java string reference typeI If the VM cannot allocate memory

I Returns NULLI OutOfMemoryError exception thrown in the VMI Native code should not continue

OSP NDK Integration (JNI), Lecture 6 25/31

Page 26: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Convert Java String to C String

I GetStringUTFChars, GetStringChars

const jbyte* str = env->GetStringUTFChars(javaString, &isCopy);

const jchar* str = env->GetStringChars(javaString, &isCopy);

I isCopyI JNI_TRUE - returned string is a copy of the chars in the

original instanceI JNI_FALSE - returned string is a direct pointer to the original

instance (pinned object in heap)I Pass NULL if it’s not important

I If the string contains only 7-bit ASCII chars you can useprintf

I If the memory allocation fails it returns NULL, throwsOutOfMemory exception

OSP NDK Integration (JNI), Lecture 6 26/31

Page 27: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Release Strings

I Free memory occupied by the C string

I ReleaseStringUTFChars, ReleaseStringChars

env->ReleaseStringUTFChars(javaString, str);

I String should be released after it is used

I Avoid memory leaks

I Frees the copy or unpins the instance (copy or not)

OSP NDK Integration (JNI), Lecture 6 27/31

Page 28: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Length and Copy in Buffer

I Get string lengthI GetStringUTFLength/GetStringLength on the jstringI Or strlen on the GetStringUTFChars result

I Copy string elements into a preallocated bufferenv->GetStringUTFRegion(javaString, 0, len, buffer);

I start index and lengthI length can be obtained with GetStringLengthI buffer is char[]I No memory allocation, no out-of-memory checks

OSP NDK Integration (JNI), Lecture 6 28/31

Page 29: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Critical Region

I GetStringCritical, ReleaseStringCritical

I Increase the probability to obtain a direct pointer to the stringI Critical Section between the calls

I Must not make blocking operationsI Must not allocate new objects in the Java VMI Disable garbage collection when holding a direct pointer to a

stringI Blocking operations or allocating objects may lead to deadlock

I No GetStringUTFCritical -> usually makes a copy of thestring

OSP NDK Integration (JNI), Lecture 6 29/31

Page 30: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Bibliography

I http://www.soi.city.ac.uk/~kloukin/IN2P3/

material/jni.pdf

I http://docs.oracle.com/javase/6/docs/technotes/

guides/jni/spec/jniTOC.html

I http://download.java.net/jdk8/docs/technotes/

guides/jni/spec/functions.html

I http://developer.android.com/training/articles/

perf-jni.html

I Onur Cinar, Pro Android C++ with the NDK, Chapter 3

I Sylvain Ratabouil, Android NDK, Beginner’s Guide, Chapter 3

OSP NDK Integration (JNI), Lecture 6 30/31

Page 31: NDK Integration (JNI) · Android NDK I Android Native Development Kit I Allows the embed C/C++ (native) code in Android applications I Implement your own native code or use existing

Keywords

I Java Native Interface

I Two-way interface

I Native methods

I Interface pointer

I Static methods

I Instance methods

I Primitive types

I Reference types

I JNI functions

I Opaque reference

I Java string reference

I Conversion operations

OSP NDK Integration (JNI), Lecture 6 31/31