SlideShare una empresa de Scribd logo
1 de 33
Android JNI/NDK
Android JNI
● Why JNI?
● What is NDK?
● Why NDK?
● Deep into JNI world.
Why JNI?
Android is put together of about equal part Java and C.
we need an easy way to bridge between these two totally different worlds
.Java offers Java Native Interface
(JNI) as a framework connecting the world of Java to the native code.
More About JNI
JNI is part of Dalvik VM, which allows native code to access java
environment. Like accessing java objects and its methods, members etc.
JNI also facilitates accessing and invoking of native methods from Java
code.
JNI Comes with Primitive and reference types.
Primitive types can be manipulated directly as these are equivalent to native
c.c++ data types
But you need special helper functions to manipulate JNI reference types.
What is NDK?
NDK is a toolchain
Cross-compiler, linker, what you need to build for ARM, x86, MIPS, etc.
NDK provides a way to bundle lib.so into your APK
The native library needs to be loadable in a secure way.
NDK "standardizes" various native platforms
It provides headers for libc, libm, libz, lliibblloogg, lliibbjjnniiggrraahhiiccss,
OpenGL/OpenSL ES,
JNI headers, minimal C++ support headers, and Android native app APIs
NDK in Action
Why NDK/JNI?
For performance
Sometimes, native code still runs faster.
For legacy support
You may have that C/C++ code you’d like to use in your app.
For access to low-level libraries
I n a rare case when there is no Java API to do something.
For cross-platform development
But Adding JNI to your app will make it more complex.
Build Process
Deep Into JNI world
Loading Native Libraries and
Registering Native Methods
Native code is usually compiled into a shared library and loaded before the
native methods can be called.
All the Native methods are declared with native keyword in java.
static {
//use either of the two methods below
System.loadLibrary(“nativelib");
System.load("/data/data/cookbook.chapter2/lib/ libNative.so");
}
Registering Native Methods
 JNIEnv Interface Pointer:
Every native method defined in native code at JNI must accept two input
parameters, the first one being a pointer to JNIEnv. The JNIEnv interface pointer is
pointing to thread-local data, which in turn points to a JNI function table shared by
all threads. This can be illustrated using the following diagram:
JNIEnv
Gateway to access all predefined JNI functions.
Access Java Fields
Invoke Java Methods.
It points to the thread’s local data, so it cannot be shared.
It can be accessible only by java threads.
Native threads must call AttachCurrentThread to attach itself to VM and to
obtain the JNIEnv interface pointer.
RegisterNatives :
 Two ways:
 1. Using Javah tool.
 2. Using RegisterNative function.
Using RegisterNative Method
Prototype:
jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod
*methods, jint nMethods);
The clazz argument is a reference to the class in which the native method is
to be registered. The methods argument is an array of the JNINativeMethod
data structure.
JNINativeMethod is defined as follows:
typedef struct {
char *name;
char *signature;
void *fnPtr;
} JNINativeMethod;
name indicates the native method name, signature is the descriptor of the
method's input argument data type and return value data type, and fnPtr is the
function pointer pointing to the native method.
The last argument, nMethods of RegisterNatives, indicates the number of
methods to register. The function returns zero to indicate success, and a
negative value otherwise.
JNI_OnLoad
 Invoke when the native library is loaded.
 It is the right and safe place to register the native methods before their
execution.
 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved)
 {
 JNIEnv* env;
 if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6)) {
 return -1;
 }
 // Get jclass with env->FindClass.
 // Register methods with env->RegisterNatives.
 return JNI_VERSION_1_6;
 }
JNI Datatypes
Manipulating strings in JNI
 Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally
different.
 Java programming language uses UTF-16 to represent strings. If a character cannot fit in a 16-bit code
value, a pair of code values named surrogate pair is used
 C strings are simply an array of bytes terminated by a null character
 The Unicode Standard is a character coding system designed to support the
worldwide interchange, processing, and display of the written texts of the
diverse languages and technical disciplines of the modern world. In addition, it
supports classical and historical texts of many written languages.
 Few JNI String Functions:
 jstring NewStringUTF(JNIEnv *env, const char *bytes);
 void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char
*buf);
 void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);
 const jbyte * GetStringUTFChars(JNIEnv *env, jstring string, jboolean
*isCopy);
Manipulating Objects in JNI
jobject AllocObject(JNIEnv *env, jclass clazz);
jobject NewObject(JNIEnv *env, jclass clazz,jmethodID
methodID, ...);
jobject NewObjectA(JNIEnv *env, jclass clazz,jmethodID
methodID, jvalue *args);
jobject NewObjectV(JNIEnv *env, jclass clazz,jmethodID
methodID, va_list args);
 The clazz argument is a reference to the Java class of which we want to create
an instance object. It cannot be an array class, which has its own set of JNI
functions.
 methodID is the constructor method ID, which can be obtained using the
GetMethodID JNI function.
Manipulating Classes in JNI
jclass FindClass(JNIEnv *env, const char *name);
 Majorly used method when writing JNI code.
 Must pass full path of class.
 If you have to call this method for finding the most used class in JNI, it is
better to Cache it.
Accessing Java Static and Instance
fileds in Native code
 jfieldID data type: jfieldID is a regular C pointer pointing to a data structure
with details hidden from developers. We should not confuse it with jobject or
its subtypes. jobject is a reference type corresponding to Object in Java,
while jfieldID doesn't have such a corresponding type in Java. However, JNI
provides functions to convert the java.lang.reflect.Field instance to jfieldID
and vice versa.
 Field descriptor: It refers to the modified UTF-8 string used to represent the
field data type. The following table summarizes the Java field types and its
corresponding field descriptors:
Accessing static fields
 JNI provides three functions to access static fields of a Java class. They
have the following prototypes:
jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz,
const char *name, const char *sig);
<NativeType> GetStatic<Type>Field(JNIEnv
*env,jclass clazz, jfieldID fieldID);
void SetStatic<Type>Field(JNIEnv *env, jclass clazz,
jfieldID fieldID,<NativeType> value);
Accessing instance field
 Accessing instance fields is similar to accessing static fields. JNI also
provides the following three functions for us:
jfieldID GetFieldID(JNIEnv *env, jclass clazz, const
char *name, const char *sig);
<NativeType> Get<Type>Field(JNIEnv *env,jobject
obj, jfieldID fieldID);
void Set<Type>Field(JNIEnv *env, jobject obj, jfieldID
fieldID, <NativeType> value);
Calling static and instance methods
from the native code
 jmethodID data type: Similar to jfieldID, jmethodID is a regular C pointer
pointing to a data structure with details hidden from the developers. JNI
provides functions to convert the java.lang.reflect.Method instance to
jmethodID and vice versa.
 Method descriptor: This is a modified UTF-8 string used to represent the
input (input arguments) data types and output (return type) data type of the
method. Method descriptors are formed by grouping all field descriptors of its
input arguments inside a "()", and appending the field descriptor of the return
type. If the return type is void, we should use "V". If there's no input
arguments, we should simply use "()", followed by the field descriptor of the
return type. For constructors, "V" should be used to represent the return
type. The following table lists a few Java methods and their corresponding
method descriptors:
Calling static methods:
 JNI provides four sets of functions for native code to call Java methods.
Their prototypes are as follows:
jmethodID GetStaticMethodID(JNIEnv *env, jclass
clazz, const char *name, const char *sig);
<NativeType> CallStatic<Type>Method(JNIEnv *env,
jclass clazz, jmethodID methodID, ...);
<NativeType> CallStatic<Type>MethodA(JNIEnv
*env, jclass clazz, jmethodID methodID, jvalue *args);
<NativeType> CallStatic<Type>MethodV(JNIEnv
*env, jclass clazz,jmethodID methodID, va_list args);
Calling instance methods:
 Calling instance methods from the native code is similar to calling static methods.
JNI also provides four sets of functions as follows:
jmethodID GetMethodID(JNIEnv *env, jclass clazz, const
char *name, const char *sig);
<NativeType> Call<Type>Method(JNIEnv *env, jobject obj,
jmethodID methodID, ...);
<NativeType> Call<Type>MethodA(JNIEnv *env,jobject
obj, jmethodID methodID, jvalue *args);
<NativeType> Call<Type>MethodV(JNIEnv *env, jobject
obj, jmethodID methodID, va_list args);
Checking errors and handling
exceptions in JNI
 JNI functions can fail because of system constraint (for example, lack of
memory) or invalid arguments (for example, passing a native UTF-8 string
when the function is expecting a UTF-16 string).
 Check for errors and exceptions: Many JNI functions return a special value
to indicate failure. For example, the FindClass function returns NULL to
indicate it failed to load the class. Many other functions do not use the return
value to signal failure; instead an exception is thrown.
 jboolean ExceptionCheck(JNIEnv *env);
 jthrowable ExceptionOccurred(JNIEnv *env);
 void ExceptionDescribe(JNIEnv *env);
Throw exceptions in the native
code:
 JNI provides two functions to throw an exception from native code. They
have the following prototypes:
jint Throw(JNIEnv *env, jthrowable obj);
jint ThrowNew(JNIEnv *env, jclass clazz, const char
*message);
 The first function accepts a reference to a jthrowable object and throws the
exception, while the second function accepts a reference to an exception
class. It will create an exception object of the clazz class with the message
argument and throw it.
Extended Error Check
 Using CheckJNI

Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv
function table pointers are switched to tables of functions that perform an
extended series of checks before calling the standard implementation.
 List of Errors that CheckJNI tool can catch:
 Arrays: attempting to allocate a negative-sized array.
 Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL
pointer to a JNI call with a non-nullable argument.
 Class names: passing anything but the “java/lang/String” style of class name to a JNI call.
 Critical calls: making a JNI call between a “critical” get and its corresponding release.
 Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.
 Exceptions: making a JNI call while there’s an exception pending.
 JNIEnv*s: using a JNIEnv* from the wrong thread.
 jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong
type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static
field to set an instance field or vice versa, or using a jfieldID from one class with instances
of another class.
Enabling CheckJNI
 Enable CheckJNI:
 For Production Builds
 adb shell setprop debug.checkjni 1
 For Engineering Builds:
 adb shell stop
 adb shell setprop dalvik.vm.checkjni true
 adb shell start
Memory Issues
 Using Libc Debug Mode
 adb shell setprop libc.debug.malloc 1
 adb shell stop
 adb shell start
 Supported libc debug mode values are
 1: Perform leak detection.
 5: Fill allocated memory to detect overruns.
 10: Fill memory and add sentinel to detect overruns.
Further Reading
 Native Threads usage
 More about references
 JNI Graphics using OpenGL
 Audio using OpenSL apis.
 http://developer.android.com/training/articles/perf-jni.html
Questions??

Más contenido relacionado

La actualidad más candente

Android booting sequece and setup and debugging
Android booting sequece and setup and debuggingAndroid booting sequece and setup and debugging
Android booting sequece and setup and debugging
Utkarsh Mankad
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
Utkarsh Mankad
 

La actualidad más candente (20)

Android Things : Building Embedded Devices
Android Things : Building Embedded DevicesAndroid Things : Building Embedded Devices
Android Things : Building Embedded Devices
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot images
 
Design and Concepts of Android Graphics
Design and Concepts of Android GraphicsDesign and Concepts of Android Graphics
Design and Concepts of Android Graphics
 
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
Android graphic system (SurfaceFlinger) : Design Pattern's perspectiveAndroid graphic system (SurfaceFlinger) : Design Pattern's perspective
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Android Binder IPC for Linux
Android Binder IPC for LinuxAndroid Binder IPC for Linux
Android Binder IPC for Linux
 
Android IPC Mechanism
Android IPC MechanismAndroid IPC Mechanism
Android IPC Mechanism
 
Android for Embedded Linux Developers
Android for Embedded Linux DevelopersAndroid for Embedded Linux Developers
Android for Embedded Linux Developers
 
Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)Embedded Android : System Development - Part II (Linux device drivers)
Embedded Android : System Development - Part II (Linux device drivers)
 
Embedded Android : System Development - Part III
Embedded Android : System Development - Part IIIEmbedded Android : System Development - Part III
Embedded Android : System Development - Part III
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
Android booting sequece and setup and debugging
Android booting sequece and setup and debuggingAndroid booting sequece and setup and debugging
Android booting sequece and setup and debugging
 
Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)Embedded Android : System Development - Part III (Audio / Video HAL)
Embedded Android : System Development - Part III (Audio / Video HAL)
 
Porting Android
Porting AndroidPorting Android
Porting Android
 
Android Binder: Deep Dive
Android Binder: Deep DiveAndroid Binder: Deep Dive
Android Binder: Deep Dive
 
Embedded Android : System Development - Part IV
Embedded Android : System Development - Part IVEmbedded Android : System Development - Part IV
Embedded Android : System Development - Part IV
 
Learning AOSP - Android Linux Device Driver
Learning AOSP - Android Linux Device DriverLearning AOSP - Android Linux Device Driver
Learning AOSP - Android Linux Device Driver
 
Android service, aidl - day 1
Android service, aidl - day 1Android service, aidl - day 1
Android service, aidl - day 1
 
RIL and Android Telephony
RIL and Android TelephonyRIL and Android Telephony
RIL and Android Telephony
 
Introduction to Android Window System
Introduction to Android Window SystemIntroduction to Android Window System
Introduction to Android Window System
 

Destacado

LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik Bytecode
Alain Leon
 

Destacado (10)

Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
Dancing with dalvik
Dancing with dalvikDancing with dalvik
Dancing with dalvik
 
Garbage Collection of Java VM
Garbage Collection of Java VMGarbage Collection of Java VM
Garbage Collection of Java VM
 
Let's talk about jni
Let's talk about jniLet's talk about jni
Let's talk about jni
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik Bytecode
 
Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011Inside Android's Dalvik VM - NEJUG Nov 2011
Inside Android's Dalvik VM - NEJUG Nov 2011
 
Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)Android internals 05 - Dalvik VM (rev_1.1)
Android internals 05 - Dalvik VM (rev_1.1)
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Google ART (Android RunTime)
Google ART (Android RunTime)Google ART (Android RunTime)
Google ART (Android RunTime)
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 

Similar a Android JNI

Similar a Android JNI (20)

Getting started with the JNI
Getting started with the JNIGetting started with the JNI
Getting started with the JNI
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Android and cpp
Android and cppAndroid and cpp
Android and cpp
 
Android ndk
Android ndkAndroid ndk
Android ndk
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Developing android apps with java 8
Developing android apps with java 8Developing android apps with java 8
Developing android apps with java 8
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014Using the android ndk - DroidCon Paris 2014
Using the android ndk - DroidCon Paris 2014
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Android JNI

  • 2. Android JNI ● Why JNI? ● What is NDK? ● Why NDK? ● Deep into JNI world.
  • 3. Why JNI? Android is put together of about equal part Java and C. we need an easy way to bridge between these two totally different worlds .Java offers Java Native Interface (JNI) as a framework connecting the world of Java to the native code.
  • 4. More About JNI JNI is part of Dalvik VM, which allows native code to access java environment. Like accessing java objects and its methods, members etc. JNI also facilitates accessing and invoking of native methods from Java code. JNI Comes with Primitive and reference types. Primitive types can be manipulated directly as these are equivalent to native c.c++ data types But you need special helper functions to manipulate JNI reference types.
  • 5. What is NDK? NDK is a toolchain Cross-compiler, linker, what you need to build for ARM, x86, MIPS, etc. NDK provides a way to bundle lib.so into your APK The native library needs to be loadable in a secure way. NDK "standardizes" various native platforms It provides headers for libc, libm, libz, lliibblloogg, lliibbjjnniiggrraahhiiccss, OpenGL/OpenSL ES, JNI headers, minimal C++ support headers, and Android native app APIs
  • 7. Why NDK/JNI? For performance Sometimes, native code still runs faster. For legacy support You may have that C/C++ code you’d like to use in your app. For access to low-level libraries I n a rare case when there is no Java API to do something. For cross-platform development But Adding JNI to your app will make it more complex.
  • 10. Loading Native Libraries and Registering Native Methods Native code is usually compiled into a shared library and loaded before the native methods can be called. All the Native methods are declared with native keyword in java. static { //use either of the two methods below System.loadLibrary(“nativelib"); System.load("/data/data/cookbook.chapter2/lib/ libNative.so"); }
  • 11. Registering Native Methods  JNIEnv Interface Pointer: Every native method defined in native code at JNI must accept two input parameters, the first one being a pointer to JNIEnv. The JNIEnv interface pointer is pointing to thread-local data, which in turn points to a JNI function table shared by all threads. This can be illustrated using the following diagram:
  • 12. JNIEnv Gateway to access all predefined JNI functions. Access Java Fields Invoke Java Methods. It points to the thread’s local data, so it cannot be shared. It can be accessible only by java threads. Native threads must call AttachCurrentThread to attach itself to VM and to obtain the JNIEnv interface pointer. RegisterNatives :  Two ways:  1. Using Javah tool.  2. Using RegisterNative function.
  • 13. Using RegisterNative Method Prototype: jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint nMethods); The clazz argument is a reference to the class in which the native method is to be registered. The methods argument is an array of the JNINativeMethod data structure. JNINativeMethod is defined as follows: typedef struct { char *name; char *signature; void *fnPtr; } JNINativeMethod; name indicates the native method name, signature is the descriptor of the method's input argument data type and return value data type, and fnPtr is the function pointer pointing to the native method. The last argument, nMethods of RegisterNatives, indicates the number of methods to register. The function returns zero to indicate success, and a negative value otherwise.
  • 14. JNI_OnLoad  Invoke when the native library is loaded.  It is the right and safe place to register the native methods before their execution.  JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved)  {  JNIEnv* env;  if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6)) {  return -1;  }  // Get jclass with env->FindClass.  // Register methods with env->RegisterNatives.  return JNI_VERSION_1_6;  }
  • 16. Manipulating strings in JNI  Strings are somewhat complicated in JNI, mainly because Java strings and C strings are internally different.  Java programming language uses UTF-16 to represent strings. If a character cannot fit in a 16-bit code value, a pair of code values named surrogate pair is used  C strings are simply an array of bytes terminated by a null character  The Unicode Standard is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages and technical disciplines of the modern world. In addition, it supports classical and historical texts of many written languages.  Few JNI String Functions:  jstring NewStringUTF(JNIEnv *env, const char *bytes);  void GetStringUTFRegion(JNIEnv *env, jstring str, jsize start, jsize len, char *buf);  void ReleaseStringUTFChars(JNIEnv *env, jstring string, const char *utf);  const jbyte * GetStringUTFChars(JNIEnv *env, jstring string, jboolean *isCopy);
  • 17. Manipulating Objects in JNI jobject AllocObject(JNIEnv *env, jclass clazz); jobject NewObject(JNIEnv *env, jclass clazz,jmethodID methodID, ...); jobject NewObjectA(JNIEnv *env, jclass clazz,jmethodID methodID, jvalue *args); jobject NewObjectV(JNIEnv *env, jclass clazz,jmethodID methodID, va_list args);  The clazz argument is a reference to the Java class of which we want to create an instance object. It cannot be an array class, which has its own set of JNI functions.  methodID is the constructor method ID, which can be obtained using the GetMethodID JNI function.
  • 18. Manipulating Classes in JNI jclass FindClass(JNIEnv *env, const char *name);  Majorly used method when writing JNI code.  Must pass full path of class.  If you have to call this method for finding the most used class in JNI, it is better to Cache it.
  • 19. Accessing Java Static and Instance fileds in Native code  jfieldID data type: jfieldID is a regular C pointer pointing to a data structure with details hidden from developers. We should not confuse it with jobject or its subtypes. jobject is a reference type corresponding to Object in Java, while jfieldID doesn't have such a corresponding type in Java. However, JNI provides functions to convert the java.lang.reflect.Field instance to jfieldID and vice versa.  Field descriptor: It refers to the modified UTF-8 string used to represent the field data type. The following table summarizes the Java field types and its corresponding field descriptors:
  • 20.
  • 21. Accessing static fields  JNI provides three functions to access static fields of a Java class. They have the following prototypes: jfieldID GetStaticFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> GetStatic<Type>Field(JNIEnv *env,jclass clazz, jfieldID fieldID); void SetStatic<Type>Field(JNIEnv *env, jclass clazz, jfieldID fieldID,<NativeType> value);
  • 22. Accessing instance field  Accessing instance fields is similar to accessing static fields. JNI also provides the following three functions for us: jfieldID GetFieldID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> Get<Type>Field(JNIEnv *env,jobject obj, jfieldID fieldID); void Set<Type>Field(JNIEnv *env, jobject obj, jfieldID fieldID, <NativeType> value);
  • 23. Calling static and instance methods from the native code  jmethodID data type: Similar to jfieldID, jmethodID is a regular C pointer pointing to a data structure with details hidden from the developers. JNI provides functions to convert the java.lang.reflect.Method instance to jmethodID and vice versa.  Method descriptor: This is a modified UTF-8 string used to represent the input (input arguments) data types and output (return type) data type of the method. Method descriptors are formed by grouping all field descriptors of its input arguments inside a "()", and appending the field descriptor of the return type. If the return type is void, we should use "V". If there's no input arguments, we should simply use "()", followed by the field descriptor of the return type. For constructors, "V" should be used to represent the return type. The following table lists a few Java methods and their corresponding method descriptors:
  • 24.
  • 25. Calling static methods:  JNI provides four sets of functions for native code to call Java methods. Their prototypes are as follows: jmethodID GetStaticMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> CallStatic<Type>Method(JNIEnv *env, jclass clazz, jmethodID methodID, ...); <NativeType> CallStatic<Type>MethodA(JNIEnv *env, jclass clazz, jmethodID methodID, jvalue *args); <NativeType> CallStatic<Type>MethodV(JNIEnv *env, jclass clazz,jmethodID methodID, va_list args);
  • 26. Calling instance methods:  Calling instance methods from the native code is similar to calling static methods. JNI also provides four sets of functions as follows: jmethodID GetMethodID(JNIEnv *env, jclass clazz, const char *name, const char *sig); <NativeType> Call<Type>Method(JNIEnv *env, jobject obj, jmethodID methodID, ...); <NativeType> Call<Type>MethodA(JNIEnv *env,jobject obj, jmethodID methodID, jvalue *args); <NativeType> Call<Type>MethodV(JNIEnv *env, jobject obj, jmethodID methodID, va_list args);
  • 27. Checking errors and handling exceptions in JNI  JNI functions can fail because of system constraint (for example, lack of memory) or invalid arguments (for example, passing a native UTF-8 string when the function is expecting a UTF-16 string).  Check for errors and exceptions: Many JNI functions return a special value to indicate failure. For example, the FindClass function returns NULL to indicate it failed to load the class. Many other functions do not use the return value to signal failure; instead an exception is thrown.  jboolean ExceptionCheck(JNIEnv *env);  jthrowable ExceptionOccurred(JNIEnv *env);  void ExceptionDescribe(JNIEnv *env);
  • 28. Throw exceptions in the native code:  JNI provides two functions to throw an exception from native code. They have the following prototypes: jint Throw(JNIEnv *env, jthrowable obj); jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);  The first function accepts a reference to a jthrowable object and throws the exception, while the second function accepts a reference to an exception class. It will create an exception object of the clazz class with the message argument and throw it.
  • 29. Extended Error Check  Using CheckJNI  Android also offers a mode called CheckJNI, where the JavaVM and JNIEnv function table pointers are switched to tables of functions that perform an extended series of checks before calling the standard implementation.  List of Errors that CheckJNI tool can catch:  Arrays: attempting to allocate a negative-sized array.  Bad pointers: passing a bad jarray/jclass/jobject/jstring to a JNI call, or passing a NULL pointer to a JNI call with a non-nullable argument.  Class names: passing anything but the “java/lang/String” style of class name to a JNI call.  Critical calls: making a JNI call between a “critical” get and its corresponding release.  Direct ByteBuffers: passing bad arguments to NewDirectByteBuffer.  Exceptions: making a JNI call while there’s an exception pending.  JNIEnv*s: using a JNIEnv* from the wrong thread.  jfieldIDs: using a NULL jfieldID, or using a jfieldID to set a field to a value of the wrong type (trying to assign a StringBuilder to a String field, say), or using a jfieldID for a static field to set an instance field or vice versa, or using a jfieldID from one class with instances of another class.
  • 30. Enabling CheckJNI  Enable CheckJNI:  For Production Builds  adb shell setprop debug.checkjni 1  For Engineering Builds:  adb shell stop  adb shell setprop dalvik.vm.checkjni true  adb shell start
  • 31. Memory Issues  Using Libc Debug Mode  adb shell setprop libc.debug.malloc 1  adb shell stop  adb shell start  Supported libc debug mode values are  1: Perform leak detection.  5: Fill allocated memory to detect overruns.  10: Fill memory and add sentinel to detect overruns.
  • 32. Further Reading  Native Threads usage  More about references  JNI Graphics using OpenGL  Audio using OpenSL apis.  http://developer.android.com/training/articles/perf-jni.html