SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
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?
Introduction to the Android NDK
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
Introduction to the Android NDK
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.

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2DianaGray10
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxNeo4j
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxNeo4j
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingMAGNIntelligence
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxKaustubhBhavsar6
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Muhammad Tiham Siddiqui
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1DianaGray10
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveIES VE
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.IPLOOK Networks
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 

Dernier (20)

UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptxGraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
GraphSummit Copenhagen 2024 - Neo4j Vision and Roadmap.pptx
 
IT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced ComputingIT Service Management (ITSM) Best Practices for Advanced Computing
IT Service Management (ITSM) Best Practices for Advanced Computing
 
How to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptxHow to become a GDSC Lead GDSC MI AOE.pptx
How to become a GDSC Lead GDSC MI AOE.pptx
 
Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)Trailblazer Community - Flows Workshop (Session 2)
Trailblazer Community - Flows Workshop (Session 2)
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
UiPath Studio Web workshop series - Day 1
UiPath Studio Web workshop series  - Day 1UiPath Studio Web workshop series  - Day 1
UiPath Studio Web workshop series - Day 1
 
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES LiveKeep Your Finger on the Pulse of Your Building's Performance with IES Live
Keep Your Finger on the Pulse of Your Building's Performance with IES Live
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.Introduction - IPLOOK NETWORKS CO., LTD.
Introduction - IPLOOK NETWORKS CO., LTD.
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 

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
  • 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
  • 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.