SlideShare a Scribd company logo
1 of 42
Download to read offline
Introduction to
the Android NDK

Sebastian Mauer
GDG Aachen

CodeFest Karlsruhe
February 20th, 2014
Who am I?
Sebastian Mauer

GDG Aachen Co-Lead
Software Engineer

CS Student
I don’t work for Google…yet
Part I:
NDK? What is that?
Android Platforms

MIPS

ARM

x86
Two kinds of Apps

Apps in the DalvikVM
(that’s the kind of apps you probably know)

Native Apps
(created using the NDK)
One VM to rule them all
•

Dalvik is a Virtual Machine (VM)

•

A VM is a common abstraction across different
hardware platforms

•

„Translates“ VM Bytecode to platform specific
instructions
It just works™
•

The DalvikVM is already optimized for the x86
Platform

•

Apps relying on the Android SDK / Dalvik Bytecode

will automatically benefit from Platform-specific
Optimizations (like SSE & Co.)
From Source to Bytecode
Java
Sourcecode
Java
Bytecode (.class)
Dalvik
Bytecode (.dex)

JAR Archive

Dalvik
VM

Java
VM
Android VM
Dalvik VM

App

App

App

App

App

App

Linux Kernel
Hardware
ONE DOES NOT SIMPLY

RUN CODE ON MULTIPLE
PLATFORMS
NOT SURE IF NDK CAN HELP ME
RUN CODE FASTER

OR MAKE THINGS EVEN MORE
COMPLICATED
Part II:
Going native. The NDK.
What’s the NDK?
•

NDK stands for Native Development Kit

•

Allows to compile C/C++ code to native (read:
platform specific) executables/libraries.

•

Build scripts/toolkit to incorporate native code in
Android apps via the Java Native Interface (JNI)

•

Has to be compiled for every platform you want to
support
But why?
•

Performance

e.g., complex algorithms, multimedia applications, games

•

Differentiation 

app that takes advantage of direct CPU/HW access

e.g., using SSSE3 for optimization

•

Fluid and lag-free animations

•

Software code reuse
Why not?
What could possibly go wrong?
•

Performance improvements are not guaranteed

•

In fact, you could make it worse (read: slower).

•

Added complexity (Java/C++ Interop, Multiple
platforms)

•

Somewhat harder to debug
What’s an NDK app?
It’s an Android application that uses
native libraries.
!

Libraries are .so files, usually found
inside libs/CPU_ABI/.
!

These libs can be generated from
native sources inside jni folder,
game engines, or required by other
3rd party libraries.
!

There is no 100% native application.
Even an application purely written
in C/C++, using native_app_glue.h,
will be executed in the context of
the Dalvik Virtual Machine.
NDK Development in a Nutshell
C/C++Code

Makefile

ndk-build

APP_ABI := all
or APP_ABI := x86

SDK APIs

Java* calls

GDB debug

through jni

Android* Applications

Java Framework

Java Application

JNI
Native Libs
Bionic C Library

NDK APIs
NDK Anatomy
Dalvik VM

Dalvik Bytecode
Java Native
Interface
(JNI)

NDK compiled binary
Native Platform
Compatibility with Standard C/C++
•

Bionic C Library:

Lighter than standard GNU C Library

Not POSIX compliant

pthread support included, but limited

No System-V IPCs

Access to Android* system properties

•

Bionic is not binary-compatible with the standard C library

•

It means you generally need to (re)compile everything
using the Android NDK toolchain
Pick One
•

By default, libstdc++ is used. It lacks: 

Standard C++ Library support (except some headers)

C++ exceptions support

RTTI support

•

Fortunately, you have other libs available with the NDK:
Runtime

Exceptions

RTTI

STL

system

No

No

No

gabi++

Yes

Yes

No

stlport

Yes

Yes

Yes

gnustl

Yes

Yes

Yes
Compile for all the platforms.
If you have the source code of your native libraries, you can compile it for several CPU
architectures by setting APP_ABI to all in the Makefile “jni/Application.mk”:!

APP_ABI=all

Put APP_ABI=all inside
Application.mk
Run ndk-build…
ARM v7a libs are built
ARM v5 libs are built
x86 libs are built
mips libs are built

The NDK will generate optimized code for all target ABIs
You can also pass APP_ABI variable directly to ndk-build, and specify each ABI:

ndk-build APP_ABI=x86
NDK
NativeActivity
• Only native code in the project
• android_main() entry point running in its
own thread
• Event loop to get input data and frame
drawing messages
/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
* event loop for receiving input events and doing other things.
*/
void android_main(struct android_app* state);
Add native methods in Java
Declare native methods in your Java classes using the ‘native’ keyword:

public native String stringFromJNI();
!

Provide a native shared library built with the NDK that contains the
methods used by your application:

!

libMyLib.so

Your application must load the shared library (before use… during class
load for example):

static {
System.loadLibrary("MyLib");
}
Variant I: Use „javah“
javah creates JNI header stubs (.h) based on the Java source files from the
compiled Java classes files
!

Example:
> javah –d jni –classpath bin/classes 
com.example.hellojni.HelloJni
!

Generates com_example_hellojni_HelloJni.h file with the following
method definition:
JNIEXPORT jstring JNICALL
Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv
*, jobject);
Variant I: Use „javah“
...
{
...
tv.setText( stringFromJNI() );
...
}

!

public native String

stringFromJNI();

static {
System.loadLibrary("hello-jni");
}

jstring
Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env,
jobject thiz )
{
return (*env)->NewStringUTF(env, "Hello from JNI !");
}
Variant II: JNI_OnLoad
• Proven method
• No more surprises after methods registration
• Less error prone when refactoring
• Add/remove native functions easily
• No symbol table issue when mixing C/C++ code
• Best spot to cache Java class object references
Variant II: JNI_OnLoad
In your library name your functions as you wish and declare the mapping with JVM methods:
jstring stringFromJNI(JNIEnv* env, jobject thiz)
{
return env->NewStringUTF("Hello from JNI !");
}

!

static JNINativeMethod exposedMethods[] = {
{"stringFromJNI","()Ljava/lang/String;",(void*)stringFromJNI},
}

!

()Ljava/lang/String; is the JNI signature of the Java* method, you can retrieve it using the
javap utility:
> javap -s -classpath binclasses -p com.example.hellojni.HelloJni
Compiled from "HelloJni.java“
…
public native java.lang.String stringFromJNI();
Signature: ()Ljava/lang/String;
…
Variant II: JNI_OnLoad
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6)
!= JNI_OK)
return JNI_ERR;

!

jclass clazz = env->FindClass("com/example/hellojni/HelloJni");
if(clazz==NULL)
return JNI_ERR;
env->RegisterNatives(clazz, exposedMethods,
sizeof(exposedMethods)/sizeof(JNINativeMethod));
env->DeleteLocalRef(clazz);

}

return JNI_VERSION_1_6;
JNI Primitives
Java Type

Native Type

Description

boolean

jboolean

unsigned 8 bits

byte

jbyte

signed 8 bits

char

jchar

unsigned 16 bits

short

jshort

signed 16 bits

int

jint

signed 32 bits

long

jlong

signed 64 bits

float

jfloat

32 bits

double

jdouble

64 bits

void

void

N/A
Memory Handling of Java Objects
Memory handling of Java* objects is done by the JVM:
!

• You only deal with references to these objects
• Each time you get a reference, you must not forget to
delete it after use
• local references are automatically deleted when the
native call returns to Java
• References are local by default
• Global references are only created by NewGlobalRef()
Creating a Java String
C:
jstring string =
(*env)->NewStringUTF(env, "new Java String");
!

C++:
jstring string = env->NewStringUTF("new Java String");

Memory is handled by the JVM, jstring is always a
reference. You can call DeleteLocalRef() on it once
you finished with it.
Convert a jstring into a C/C++ String
const char *nativeString = (*env)>GetStringUTFChars(javaString, null);
…
(*env)->ReleaseStringUTFChars(env, javaString, nativeString);
Call a Java Method
On an object instance:
jclass clazz = (*env)->GetObjectClass(env, obj);
jmethodID mid = (*env)->GetMethodID(env, clazz, "methodName",
"(…)…");
if (mid != NULL)
(*env)->Call<Type>Method(env, obj, mid, parameters…);
!
Static call:
jclass clazz = (*env)->FindClass(env, "java/lang/String");
jmethodID mid = (*env)->GetStaticMethodID(env, clazz,
"methodName", "(…)…");
if (mid != NULL)
(*env)->CallStatic<Type>Method(env, clazz, mid,
parameters…);
!
• (…)…: method signature
• parameters: list of parameters expected by the Java* method
• <Type>: Java method return type
Handling Java Exceptions
// call to java methods may throw Java exceptions
jthrowable ex = (*env)->ExceptionOccurred(env);
if (ex!=NULL) {
(*env)->ExceptionClear(env);
// deal with exception
}
!

(*env)->DeleteLocalRef(env, ex);
Throw a Java Exception
jclass clazz =
(*env->FindClass(env, "java/lang/Exception");
!

if (clazz!=NULL)
(*env)->ThrowNew(env, clazz, "Message");
The exception will be thrown only when the JNI call returns to Java*, it
will not break the current native code execution.
Demo
Q&A
Thanks for your attention.

More Related Content

What's hot

Android NDK and the x86 Platform
Android NDK and the x86 PlatformAndroid NDK and the x86 Platform
Android NDK and the x86 PlatformSebastian Mauer
 
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)DroidConTLV
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDKSebastian Mauer
 
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 2014Paris Android User Group
 
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 machineChun-Yu Wang
 
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 toolGabor Paller
 
How to reverse engineer Android applications
How to reverse engineer Android applicationsHow to reverse engineer Android applications
How to reverse engineer Android applicationshubx
 
Advanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAdvanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAlex Matrosov
 
Android Developer Meetup
Android Developer MeetupAndroid Developer Meetup
Android Developer MeetupMedialets
 
Toward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareToward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareZongXian Shen
 
Android ndk - Introduction
Android ndk  - IntroductionAndroid ndk  - Introduction
Android ndk - IntroductionRakesh Jha
 
Reverse engineering android apps
Reverse engineering android appsReverse engineering android apps
Reverse engineering android appsPranay Airan
 
Object Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorerObject Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorerAlex Matrosov
 
Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Tetsuyuki Kobayashi
 
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS EngineZongXian Shen
 
Guide: How to Build OpenCV 3.0.0
Guide: How to Build OpenCV 3.0.0Guide: How to Build OpenCV 3.0.0
Guide: How to Build OpenCV 3.0.0André Moreira
 
Hierarchy Viewer Internals
Hierarchy Viewer InternalsHierarchy Viewer Internals
Hierarchy Viewer InternalsKyungmin Lee
 
Intoduction to java
Intoduction to javaIntoduction to java
Intoduction to javajalinder123
 

What's hot (20)

Android NDK and the x86 Platform
Android NDK and the x86 PlatformAndroid NDK and the x86 Platform
Android NDK and the x86 Platform
 
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)
 
Introduction to the Android NDK
Introduction to the Android NDKIntroduction to the Android NDK
Introduction to the Android NDK
 
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
 
Android NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo NativoAndroid NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo Nativo
 
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
 
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
 
How to reverse engineer Android applications
How to reverse engineer Android applicationsHow to reverse engineer Android applications
How to reverse engineer Android applications
 
Advanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/GapzAdvanced Evasion Techniques by Win32/Gapz
Advanced Evasion Techniques by Win32/Gapz
 
Android Developer Meetup
Android Developer MeetupAndroid Developer Meetup
Android Developer Meetup
 
Toward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareToward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malware
 
Android ndk - Introduction
Android ndk  - IntroductionAndroid ndk  - Introduction
Android ndk - Introduction
 
Reverse engineering android apps
Reverse engineering android appsReverse engineering android apps
Reverse engineering android apps
 
Object Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorerObject Oriented Code RE with HexraysCodeXplorer
Object Oriented Code RE with HexraysCodeXplorer
 
.NET Vs J2EE
.NET Vs J2EE.NET Vs J2EE
.NET Vs J2EE
 
Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'Android is NOT just 'Java on Linux'
Android is NOT just 'Java on Linux'
 
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
 
Guide: How to Build OpenCV 3.0.0
Guide: How to Build OpenCV 3.0.0Guide: How to Build OpenCV 3.0.0
Guide: How to Build OpenCV 3.0.0
 
Hierarchy Viewer Internals
Hierarchy Viewer InternalsHierarchy Viewer Internals
Hierarchy Viewer Internals
 
Intoduction to java
Intoduction to javaIntoduction to java
Intoduction to java
 

Similar to Introduction to the Android NDK

NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)Ron Munitz
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)Ron Munitz
 
Writing Android Libraries
Writing Android LibrariesWriting Android Libraries
Writing Android Librariesemanuelez
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application DevelopmentRamesh Prasad
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting StartedRakesh Madugula
 
Getting started with the NDK
Getting started with the NDKGetting started with the NDK
Getting started with the NDKKirill Kounik
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operatorkamal kotecha
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Androidcoolmirza143
 
Android on IA devices and Intel Tools
Android on IA devices and Intel ToolsAndroid on IA devices and Intel Tools
Android on IA devices and Intel ToolsXavier Hallade
 
DLL Design with Building Blocks
DLL Design with Building BlocksDLL Design with Building Blocks
DLL Design with Building BlocksMax Kleiner
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)Shaharyar khan
 
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 worthIdan Sheinberg
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeAlain Leon
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptRajeshSukte1
 

Similar to Introduction to the Android NDK (20)

Android ndk
Android ndkAndroid ndk
Android ndk
 
NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)NDK Primer (AnDevCon Boston 2014)
NDK Primer (AnDevCon Boston 2014)
 
Getting Native with NDK
Getting Native with NDKGetting Native with NDK
Getting Native with NDK
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
109842496 jni
109842496 jni109842496 jni
109842496 jni
 
Writing Android Libraries
Writing Android LibrariesWriting Android Libraries
Writing Android Libraries
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
Getting started with the NDK
Getting started with the NDKGetting started with the NDK
Getting started with the NDK
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Android
 
Android on IA devices and Intel Tools
Android on IA devices and Intel ToolsAndroid on IA devices and Intel Tools
Android on IA devices and Intel Tools
 
DLL Design with Building Blocks
DLL Design with Building BlocksDLL Design with Building Blocks
DLL Design with Building Blocks
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
JAVA First Day
JAVA First DayJAVA First Day
JAVA First Day
 
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
 
LinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik BytecodeLinkedIn - Disassembling Dalvik Bytecode
LinkedIn - Disassembling Dalvik Bytecode
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
PPS Java Overview Unit I.ppt
PPS Java Overview Unit I.pptPPS Java Overview Unit I.ppt
PPS Java Overview Unit I.ppt
 

More from BeMyApp

Introduction to epid
Introduction to epidIntroduction to epid
Introduction to epidBeMyApp
 
Introduction ciot workshop premeetup
Introduction ciot workshop premeetupIntroduction ciot workshop premeetup
Introduction ciot workshop premeetupBeMyApp
 
Présentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM WatsonPrésentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM WatsonBeMyApp
 
Crédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et ParcoursCrédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et ParcoursBeMyApp
 
Cisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - IntroCisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - IntroBeMyApp
 
Tumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensembleTumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensembleBeMyApp
 
Building your first game in Unity 3d by Sarah Sexton
Building your first game in Unity 3d  by Sarah SextonBuilding your first game in Unity 3d  by Sarah Sexton
Building your first game in Unity 3d by Sarah SextonBeMyApp
 
Using intel's real sense to create games with natural user interfaces justi...
Using intel's real sense to create games with natural user interfaces   justi...Using intel's real sense to create games with natural user interfaces   justi...
Using intel's real sense to create games with natural user interfaces justi...BeMyApp
 
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon CollinsIntroduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon CollinsBeMyApp
 
Audio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy TouchAudio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy TouchBeMyApp
 
Shaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestShaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestBeMyApp
 
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart CityBeMyApp
 
Tools to Save Time
Tools to Save TimeTools to Save Time
Tools to Save TimeBeMyApp
 
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateurBeMyApp
 
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...BeMyApp
 
[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technology[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technologyBeMyApp
 
HP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit RecapHP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit RecapBeMyApp
 
Webinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco MarcellinoWebinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco MarcellinoBeMyApp
 
HP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond FirewallsHP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond FirewallsBeMyApp
 
HP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pillHP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pillBeMyApp
 

More from BeMyApp (20)

Introduction to epid
Introduction to epidIntroduction to epid
Introduction to epid
 
Introduction ciot workshop premeetup
Introduction ciot workshop premeetupIntroduction ciot workshop premeetup
Introduction ciot workshop premeetup
 
Présentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM WatsonPrésentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM Watson
 
Crédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et ParcoursCrédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et Parcours
 
Cisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - IntroCisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - Intro
 
Tumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensembleTumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensemble
 
Building your first game in Unity 3d by Sarah Sexton
Building your first game in Unity 3d  by Sarah SextonBuilding your first game in Unity 3d  by Sarah Sexton
Building your first game in Unity 3d by Sarah Sexton
 
Using intel's real sense to create games with natural user interfaces justi...
Using intel's real sense to create games with natural user interfaces   justi...Using intel's real sense to create games with natural user interfaces   justi...
Using intel's real sense to create games with natural user interfaces justi...
 
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon CollinsIntroduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
 
Audio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy TouchAudio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy Touch
 
Shaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestShaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the Best
 
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
 
Tools to Save Time
Tools to Save TimeTools to Save Time
Tools to Save Time
 
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
 
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
 
[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technology[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technology
 
HP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit RecapHP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit Recap
 
Webinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco MarcellinoWebinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco Marcellino
 
HP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond FirewallsHP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond Firewalls
 
HP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pillHP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pill
 

Recently uploaded

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Introduction to the Android NDK

  • 1. Introduction to the Android NDK Sebastian Mauer GDG Aachen CodeFest Karlsruhe February 20th, 2014
  • 2. Who am I? Sebastian Mauer GDG Aachen Co-Lead Software Engineer CS Student I don’t work for Google…yet
  • 3. Part I: NDK? What is that?
  • 5. Two kinds of Apps Apps in the DalvikVM (that’s the kind of apps you probably know) Native Apps (created using the NDK)
  • 6. One VM to rule them all • Dalvik is a Virtual Machine (VM) • A VM is a common abstraction across different hardware platforms • „Translates“ VM Bytecode to platform specific instructions
  • 7. It just works™ • The DalvikVM is already optimized for the x86 Platform • Apps relying on the Android SDK / Dalvik Bytecode
 will automatically benefit from Platform-specific Optimizations (like SSE & Co.)
  • 8. From Source to Bytecode Java Sourcecode Java Bytecode (.class) Dalvik Bytecode (.dex) JAR Archive Dalvik VM Java VM
  • 10. ONE DOES NOT SIMPLY RUN CODE ON MULTIPLE PLATFORMS
  • 11. NOT SURE IF NDK CAN HELP ME RUN CODE FASTER OR MAKE THINGS EVEN MORE COMPLICATED
  • 13. What’s the NDK? • NDK stands for Native Development Kit • Allows to compile C/C++ code to native (read: platform specific) executables/libraries. • Build scripts/toolkit to incorporate native code in Android apps via the Java Native Interface (JNI) • Has to be compiled for every platform you want to support
  • 14. But why? • Performance
 e.g., complex algorithms, multimedia applications, games • Differentiation 
 app that takes advantage of direct CPU/HW access
 e.g., using SSSE3 for optimization • Fluid and lag-free animations • Software code reuse
  • 16.
  • 17. What could possibly go wrong? • Performance improvements are not guaranteed • In fact, you could make it worse (read: slower). • Added complexity (Java/C++ Interop, Multiple platforms) • Somewhat harder to debug
  • 18.
  • 19. What’s an NDK app? It’s an Android application that uses native libraries. ! Libraries are .so files, usually found inside libs/CPU_ABI/. ! These libs can be generated from native sources inside jni folder, game engines, or required by other 3rd party libraries. ! There is no 100% native application. Even an application purely written in C/C++, using native_app_glue.h, will be executed in the context of the Dalvik Virtual Machine.
  • 20. NDK Development in a Nutshell C/C++Code Makefile ndk-build APP_ABI := all or APP_ABI := x86 SDK APIs Java* calls GDB debug through jni Android* Applications Java Framework Java Application JNI Native Libs Bionic C Library NDK APIs
  • 21. NDK Anatomy Dalvik VM Dalvik Bytecode Java Native Interface (JNI) NDK compiled binary Native Platform
  • 22. Compatibility with Standard C/C++ • Bionic C Library:
 Lighter than standard GNU C Library
 Not POSIX compliant
 pthread support included, but limited
 No System-V IPCs
 Access to Android* system properties • Bionic is not binary-compatible with the standard C library • It means you generally need to (re)compile everything using the Android NDK toolchain
  • 23. Pick One • By default, libstdc++ is used. It lacks: 
 Standard C++ Library support (except some headers)
 C++ exceptions support
 RTTI support • Fortunately, you have other libs available with the NDK: Runtime Exceptions RTTI STL system No No No gabi++ Yes Yes No stlport Yes Yes Yes gnustl Yes Yes Yes
  • 24. Compile for all the platforms. If you have the source code of your native libraries, you can compile it for several CPU architectures by setting APP_ABI to all in the Makefile “jni/Application.mk”:! APP_ABI=all Put APP_ABI=all inside Application.mk Run ndk-build… ARM v7a libs are built ARM v5 libs are built x86 libs are built mips libs are built The NDK will generate optimized code for all target ABIs You can also pass APP_ABI variable directly to ndk-build, and specify each ABI: ndk-build APP_ABI=x86
  • 25. NDK
  • 26. NativeActivity • Only native code in the project • android_main() entry point running in its own thread • Event loop to get input data and frame drawing messages /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state);
  • 27. Add native methods in Java Declare native methods in your Java classes using the ‘native’ keyword:
 public native String stringFromJNI(); ! Provide a native shared library built with the NDK that contains the methods used by your application:
 ! libMyLib.so Your application must load the shared library (before use… during class load for example):
 static { System.loadLibrary("MyLib"); }
  • 28. Variant I: Use „javah“ javah creates JNI header stubs (.h) based on the Java source files from the compiled Java classes files ! Example: > javah –d jni –classpath bin/classes com.example.hellojni.HelloJni ! Generates com_example_hellojni_HelloJni.h file with the following method definition: JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv *, jobject);
  • 29. Variant I: Use „javah“ ... { ... tv.setText( stringFromJNI() ); ... } ! public native String stringFromJNI(); static { System.loadLibrary("hello-jni"); } jstring Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env, jobject thiz ) { return (*env)->NewStringUTF(env, "Hello from JNI !"); }
  • 30. Variant II: JNI_OnLoad • Proven method • No more surprises after methods registration • Less error prone when refactoring • Add/remove native functions easily • No symbol table issue when mixing C/C++ code • Best spot to cache Java class object references
  • 31. Variant II: JNI_OnLoad In your library name your functions as you wish and declare the mapping with JVM methods: jstring stringFromJNI(JNIEnv* env, jobject thiz) { return env->NewStringUTF("Hello from JNI !"); } ! static JNINativeMethod exposedMethods[] = { {"stringFromJNI","()Ljava/lang/String;",(void*)stringFromJNI}, } ! ()Ljava/lang/String; is the JNI signature of the Java* method, you can retrieve it using the javap utility: > javap -s -classpath binclasses -p com.example.hellojni.HelloJni Compiled from "HelloJni.java“ … public native java.lang.String stringFromJNI(); Signature: ()Ljava/lang/String; …
  • 32. Variant II: JNI_OnLoad extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; ! jclass clazz = env->FindClass("com/example/hellojni/HelloJni"); if(clazz==NULL) return JNI_ERR; env->RegisterNatives(clazz, exposedMethods, sizeof(exposedMethods)/sizeof(JNINativeMethod)); env->DeleteLocalRef(clazz); } return JNI_VERSION_1_6;
  • 33. JNI Primitives Java Type Native Type Description boolean jboolean unsigned 8 bits byte jbyte signed 8 bits char jchar unsigned 16 bits short jshort signed 16 bits int jint signed 32 bits long jlong signed 64 bits float jfloat 32 bits double jdouble 64 bits void void N/A
  • 34. Memory Handling of Java Objects Memory handling of Java* objects is done by the JVM: ! • You only deal with references to these objects • Each time you get a reference, you must not forget to delete it after use • local references are automatically deleted when the native call returns to Java • References are local by default • Global references are only created by NewGlobalRef()
  • 35. Creating a Java String C: jstring string = (*env)->NewStringUTF(env, "new Java String"); ! C++: jstring string = env->NewStringUTF("new Java String"); Memory is handled by the JVM, jstring is always a reference. You can call DeleteLocalRef() on it once you finished with it.
  • 36. Convert a jstring into a C/C++ String const char *nativeString = (*env)>GetStringUTFChars(javaString, null); … (*env)->ReleaseStringUTFChars(env, javaString, nativeString);
  • 37. Call a Java Method On an object instance: jclass clazz = (*env)->GetObjectClass(env, obj); jmethodID mid = (*env)->GetMethodID(env, clazz, "methodName", "(…)…"); if (mid != NULL) (*env)->Call<Type>Method(env, obj, mid, parameters…); ! Static call: jclass clazz = (*env)->FindClass(env, "java/lang/String"); jmethodID mid = (*env)->GetStaticMethodID(env, clazz, "methodName", "(…)…"); if (mid != NULL) (*env)->CallStatic<Type>Method(env, clazz, mid, parameters…); ! • (…)…: method signature • parameters: list of parameters expected by the Java* method • <Type>: Java method return type
  • 38. Handling Java Exceptions // call to java methods may throw Java exceptions jthrowable ex = (*env)->ExceptionOccurred(env); if (ex!=NULL) { (*env)->ExceptionClear(env); // deal with exception } ! (*env)->DeleteLocalRef(env, ex);
  • 39. Throw a Java Exception jclass clazz = (*env->FindClass(env, "java/lang/Exception"); ! if (clazz!=NULL) (*env)->ThrowNew(env, clazz, "Message"); The exception will be thrown only when the JNI call returns to Java*, it will not break the current native code execution.
  • 40. Demo
  • 41. Q&A
  • 42. Thanks for your attention.