SlideShare a Scribd company logo
1 of 36
Download to read offline
Fullstack as a service
Getting Started with the JNI
Java Native Interface
Kirill Kounik
- I am part of 12+ people strong Tikal's Android
group.
- Experience in startup and medium sized
companies
- 6.5 years in Sun Microsystems with JME
technology
- Java, client, low level
- Graduate of Technion in Computer Science
WHO AM I?
Agenda
What JNI can do
Simple example
JNI basics
Native JNI functions
Java type mapping
Inspecting classes, calling Java methods
Processing Exceptions
Goal
When JNI is useful - Pros
The standard Java class library does not support the platform-dependent
features needed by the application.
You already have a library written in another language, and wish to make it
accessible to Java code through the JNI.
You want to implement a small portion of time-critical code in a lower-level
language.
When JNI is useful - Cons
You program is not platform independent anymore
You are using low level language with all its drawbacks
JNI call costs time http://stackoverflow.com/questions/13973035/what-is-the-
quantitative-overhead-of-making-a-jni-call
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.3) (7u9-2.3.3-1)
OpenJDK Server VM (build 23.2-b09, mixed mode)
Linux visor 3.2.0-4-686-pae #1 SMP Debian 3.2.32-1 i686 GNU/Linux
JNI access to JVM
Native JNI code leaves side by side with the JVM and has access to its structures.
Create, inspect, and update Java objects (including arrays and strings).
Call Java methods.
Catch and throw exceptions.
Load classes and obtain class information.
Perform runtime type checking.
Create threads visible to JVM
Native method in Java class
package jni;
public class CHelloWorld {
native String hello();
static {
System.loadLibrary("jni_CHello");
}
public static void main(String[] args) {
CHelloWorld chw = new CHelloWorld();
System.out.println(chw.hello());
}
}
Native method implementation
#include <jni.h>
/*
* Class: jni_CHelloWorld
* Method: hello
* Signature: ()Ljava/lang/String;
*/
jstring Java_jni_CHelloWorld_hello(JNIEnv *env, jobject thiz)
{
return (*env)->NewStringUTF(env, "hello, world (from JNI)");
}
Native method implementation
jstring ← Java return type
Java_jni_CHelloWorld_hello( JNIEnv* env, jobject thiz )
Naming convention for JNI
functions “this” object
reference
Pointer to JNI
environment
for JNI
functions
access
Method overloading
package jni;
public class CHelloWorld {
native String hello();
native String hello(String what, int count);
. . .
}
Method overloading
/*
* Class: jni_CHelloWorld
* Method: hello
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_jni_CHelloWorld_hello__ (JNIEnv *, jobject);
/*
* Class: jni_CHelloWorld
* Method: hello
* Signature: (Ljava/lang/String;I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_jni_CHelloWorld_hello__Ljava_lang_String_2I
(JNIEnv *, jobject, jstring, jint);
Resolving method names
A native method name is concatenated from the following components:
• the prefix Java_
• a mangled fully-qualified class name
• an underscore (“_”) separator
• a mangled method name
• for overloaded native methods, two underscores (“__”) followed by the
mangled argument signature
javah tool
The javah command conveniently generates C header and source files that are
needed to implement native methods. (Generated files not really required)
$ javah -d .srcnative -cp .binjava jni.CHelloWorld
JNI native function arguments
The JNI interface pointer is the first argument to native methods. The JNI
interface pointer is of type JNIEnv.
The second argument differs depending on whether the native method is static
or nonstatic.
• The second argument to a nonstatic native method is a reference to the object.
• The second argument to a static native method is a reference to its Java class.
JNI native function arguments
The remaining arguments correspond to regular Java method arguments.
The native method call passes its result back to the calling routine via the return
value
JNIEvn*
Reference to JNI environment, which lets you access all the JNI functions. Used
for:
Create new objects
Access Fields inside Java classes
Invoke Java Methods.
It points to the thread’s local data, so it cannot be shared between threads.
Note on C++
#include <jni.h>
extern ”C” {
jstring Java_jni_CHelloWorld_hello(JNIEnv *env, jobject thiz)
{
return env->NewStringUTF("hello, world (from JNI)");
}
}
Arguments of a primitive type passed by value
Java Type Native Type Constants
boolean jboolean JNI_FALSE, JNI_TRUE
byte jbyte
char jchar
short jshort
int jint
long jlong
float jfloat
double jdouble
void void
jsize scalar values and sizes
Reference types
Reference types passed “by reference”. Here is native method hierarchy:
Accessing Strings
jstring Java_jni_CHelloWorld_hello__Ljava_lang_String_2I
(JNIEnv* env, jobject thiz, jstring what, jint count) {
char dest[30];
/* Obtain string characters */
const char* str = (*env)->GetStringUTFChars(env, what, 0);
strcpy(dest, “hello, “);
strncat(dest, str, 22);
/* Relase characters to avoid memory leak */
(*env)->ReleaseStringUTFChars(env, what, str);
return (*env)->NewStringUTF(env, dest);
}
Local and Global References
• Every argument passed to JNI call is a local reference that is valid only for the
duration of the call. This applies to all sub-classes of jobject, including
jclass, jstring, and jarray.
• In order to get Global references:
jobject NewGlobalRef(JNIEnv *env, jobject obj);
• Global reference is live until it is not explicitly released
void DeleteGlobalRef(JNIEnv *env, jobject globalRef);
Local and Global References
• Do "not excessively allocate" local references.
• Free local references them manually with DeleteLocalRef()
• The implementation is only required to reserve slots for 16 local references,
• if you need more than that you should either delete as you go or use
EnsureLocalCapacity/PushLocalFrame to reserve more
Passing array arguments
/* private native long sumAll(int[] numbers); */
jlong Java_jni_CHelloWorld_sumAll(JNIEnv *env, jobject thiz, jintArray
values_) {
jint *values = (*env)->GetIntArrayElements(env, values_, NULL);
jsize len = (*env)->GetArrayLength(env, values_);
jlong sum = 0;
int i;
for (i = 0; i < len; i++) {
sum += values[i];
}
(*env)->ReleaseIntArrayElements(env, values_, values, 0);
return sum;
}
On class file structure
Goal: read or write class or instance variables from the JNI code
Goal: call java methods from the JNI code
Java VM type signatures:
Z boolean
B byte
C char
S short
I int
J long
F float
D double
Lfully-qualified-class; fully-qualified-class
[type type[]
(arg-types)ret-type method type
VM Signature example
Example Java method signature
long foo(int n, String s, int[] arr);
JVM Type signature:
(ILjava/lang/String;[I)J
javap tool
javap is Java Class File disassembler tool that comes to rescue
$ javap -s -p -cp .binjava jni.CHelloWorld
Accessing class/instance members
Find correct class object
Find member index, either method or field
Use correct instance object
Do method invocation or field access
Non-static method invocation
- Find class of your object
jclass cl = (*env)->GetObjectClass(env, textView);
- Find method
jmethodID methodId = (*env)->GetMethodID(env, cl, "setText", "(Ljava/lang/CharSequence;)V");
- Call your method using correct JNI function
(*env)->CallVoidMethod(env, textView, methodId, … );
Static method invocation
- Find correct class if needed
jclass cl = FindClass(env, "java/lang/String");
- Find static method
jmethodID methodId = (*env)->GetStaticMethodID(env, cl, "copyValueOf", "([C)Ljava/lang/String;");
- Call using correct invocation method
jobject o = (*env)->CallStaticObjectMethod(env, cl, methodId, /* NativeTypes */ … );
Accessing instance fields
- Find object’s class
- Get field id
jfieldID fieldId = (*env)->GetFieldID(env, clazz, "chars", "[C");
- Get/set field value using correct method
jobject o = (*env)->GetObjectField(env, instance, jfieldID );
(*env)->SetObjectField(env, instance, jfieldId, /* NativeType */ value);
Accessing static fields
- Find correct class if needed
- Find static field
jfieldID fieldId = (*env)->GetStaticFieldID(env, clazz, "count", "I");
- Get/set static field value using correct method
jint i = (*env)->GetStaticIntField(env, instance, jfieldID );
(*env)->SetStaticIntField(env, instance, jfieldId, /* NativeType */ 5);
Checking for errors
Calling most of JNI functions is not allowed if exception is pending and will cause
crash. When there is a chance on an exception JNI must check for the exception
state
jboolean ExceptionCheck(JNIEnv *env);
jthrowable ExceptionOccurred(JNIEnv *env);
void ExceptionClear(JNIEnv *env);
void ExceptionDescribe(JNIEnv *env);
Throwing an exception
jint Throw(JNIEnv *env, jthrowable obj);
jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);
void FatalError(JNIEnv *env, const char *msg);
Usefull references
https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx
http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/jniTOC.html
http://www.ibm.com/support/knowledgecenter/SSYKE2_7.0.0/com.ibm.java.lnx.7
0.doc/diag/understanding/jni.html

More Related Content

What's hot

Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONLalitkumar_98
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonSujith Kumar
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 

What's hot (19)

Java Notes
Java Notes Java Notes
Java Notes
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
About Python
About PythonAbout Python
About Python
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Core java
Core javaCore java
Core java
 

Viewers also liked

Jni – java native interface
Jni – java native interfaceJni – java native interface
Jni – java native interfaceJernej Virag
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesNebojša Vukšić
 
Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)Peter Lawrey
 
Network Automation with Salt and NAPALM: a self-resilient network
Network Automation with Salt and NAPALM: a self-resilient networkNetwork Automation with Salt and NAPALM: a self-resilient network
Network Automation with Salt and NAPALM: a self-resilient networkAPNIC
 
BDX 2016 - Tzach zohar @ kenshoo
BDX 2016 - Tzach zohar  @ kenshooBDX 2016 - Tzach zohar  @ kenshoo
BDX 2016 - Tzach zohar @ kenshooIdo Shilon
 
手把手帶你學Docker 03042017
手把手帶你學Docker 03042017手把手帶你學Docker 03042017
手把手帶你學Docker 03042017Paul Chao
 
BUD17-416: Benchmark and profiling in OP-TEE
BUD17-416: Benchmark and profiling in OP-TEE BUD17-416: Benchmark and profiling in OP-TEE
BUD17-416: Benchmark and profiling in OP-TEE Linaro
 
Real World Java 9 (QCon London)
Real World Java 9 (QCon London)Real World Java 9 (QCon London)
Real World Java 9 (QCon London)Trisha Gee
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017Arun Gupta
 
Introduction to Apache Mesos
Introduction to Apache MesosIntroduction to Apache Mesos
Introduction to Apache MesosJoe Stein
 
BUD17-218: Scheduler Load tracking update and improvement
BUD17-218: Scheduler Load tracking update and improvement BUD17-218: Scheduler Load tracking update and improvement
BUD17-218: Scheduler Load tracking update and improvement Linaro
 
BUD17-300: Journey of a packet
BUD17-300: Journey of a packetBUD17-300: Journey of a packet
BUD17-300: Journey of a packetLinaro
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
London Adapt or Die: Kubernetes, Containers and Cloud - The MoD Story
London Adapt or Die: Kubernetes, Containers and Cloud - The MoD StoryLondon Adapt or Die: Kubernetes, Containers and Cloud - The MoD Story
London Adapt or Die: Kubernetes, Containers and Cloud - The MoD StoryApigee | Google Cloud
 
BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64
BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64 BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64
BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64 Linaro
 

Viewers also liked (20)

Jni – java native interface
Jni – java native interfaceJni – java native interface
Jni – java native interface
 
Android JNI
Android JNIAndroid JNI
Android JNI
 
The Awesomeness of Go
The Awesomeness of GoThe Awesomeness of Go
The Awesomeness of Go
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java I/O
Java I/OJava I/O
Java I/O
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 
Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)Thread Safe Interprocess Shared Memory in Java (in 7 mins)
Thread Safe Interprocess Shared Memory in Java (in 7 mins)
 
Network Automation with Salt and NAPALM: a self-resilient network
Network Automation with Salt and NAPALM: a self-resilient networkNetwork Automation with Salt and NAPALM: a self-resilient network
Network Automation with Salt and NAPALM: a self-resilient network
 
BDX 2016 - Tzach zohar @ kenshoo
BDX 2016 - Tzach zohar  @ kenshooBDX 2016 - Tzach zohar  @ kenshoo
BDX 2016 - Tzach zohar @ kenshoo
 
手把手帶你學Docker 03042017
手把手帶你學Docker 03042017手把手帶你學Docker 03042017
手把手帶你學Docker 03042017
 
BUD17-416: Benchmark and profiling in OP-TEE
BUD17-416: Benchmark and profiling in OP-TEE BUD17-416: Benchmark and profiling in OP-TEE
BUD17-416: Benchmark and profiling in OP-TEE
 
Real World Java 9 (QCon London)
Real World Java 9 (QCon London)Real World Java 9 (QCon London)
Real World Java 9 (QCon London)
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017
 
Introduction to Apache Mesos
Introduction to Apache MesosIntroduction to Apache Mesos
Introduction to Apache Mesos
 
BUD17-218: Scheduler Load tracking update and improvement
BUD17-218: Scheduler Load tracking update and improvement BUD17-218: Scheduler Load tracking update and improvement
BUD17-218: Scheduler Load tracking update and improvement
 
BUD17-300: Journey of a packet
BUD17-300: Journey of a packetBUD17-300: Journey of a packet
BUD17-300: Journey of a packet
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Hadoop on-mesos
Hadoop on-mesosHadoop on-mesos
Hadoop on-mesos
 
London Adapt or Die: Kubernetes, Containers and Cloud - The MoD Story
London Adapt or Die: Kubernetes, Containers and Cloud - The MoD StoryLondon Adapt or Die: Kubernetes, Containers and Cloud - The MoD Story
London Adapt or Die: Kubernetes, Containers and Cloud - The MoD Story
 
BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64
BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64 BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64
BUD17-209: Reliability, Availability, and Serviceability (RAS) on ARM64
 

Similar to Getting Started with the Java Native Interface (JNI

Similar to Getting Started with the Java Native Interface (JNI (20)

Android JNI
Android JNIAndroid JNI
Android JNI
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Let's talk about jni
Let's talk about jniLet's talk about jni
Let's talk about jni
 
Android and cpp
Android and cppAndroid and cpp
Android and cpp
 
NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)NDK Primer (Wearable DevCon 2014)
NDK Primer (Wearable DevCon 2014)
 
core java
core javacore java
core java
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
JNI 使用淺談
JNI 使用淺談JNI 使用淺談
JNI 使用淺談
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Cse java
Cse javaCse java
Cse java
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
JNA
JNAJNA
JNA
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Java Intro
Java IntroJava Intro
Java Intro
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 

Recently uploaded

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Recently uploaded (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

Getting Started with the Java Native Interface (JNI

  • 1. Fullstack as a service Getting Started with the JNI Java Native Interface Kirill Kounik
  • 2. - I am part of 12+ people strong Tikal's Android group. - Experience in startup and medium sized companies - 6.5 years in Sun Microsystems with JME technology - Java, client, low level - Graduate of Technion in Computer Science WHO AM I?
  • 3. Agenda What JNI can do Simple example JNI basics Native JNI functions Java type mapping Inspecting classes, calling Java methods Processing Exceptions
  • 5. When JNI is useful - Pros The standard Java class library does not support the platform-dependent features needed by the application. You already have a library written in another language, and wish to make it accessible to Java code through the JNI. You want to implement a small portion of time-critical code in a lower-level language.
  • 6. When JNI is useful - Cons You program is not platform independent anymore You are using low level language with all its drawbacks JNI call costs time http://stackoverflow.com/questions/13973035/what-is-the- quantitative-overhead-of-making-a-jni-call java version "1.7.0_09" OpenJDK Runtime Environment (IcedTea7 2.3.3) (7u9-2.3.3-1) OpenJDK Server VM (build 23.2-b09, mixed mode) Linux visor 3.2.0-4-686-pae #1 SMP Debian 3.2.32-1 i686 GNU/Linux
  • 7. JNI access to JVM Native JNI code leaves side by side with the JVM and has access to its structures. Create, inspect, and update Java objects (including arrays and strings). Call Java methods. Catch and throw exceptions. Load classes and obtain class information. Perform runtime type checking. Create threads visible to JVM
  • 8. Native method in Java class package jni; public class CHelloWorld { native String hello(); static { System.loadLibrary("jni_CHello"); } public static void main(String[] args) { CHelloWorld chw = new CHelloWorld(); System.out.println(chw.hello()); } }
  • 9. Native method implementation #include <jni.h> /* * Class: jni_CHelloWorld * Method: hello * Signature: ()Ljava/lang/String; */ jstring Java_jni_CHelloWorld_hello(JNIEnv *env, jobject thiz) { return (*env)->NewStringUTF(env, "hello, world (from JNI)"); }
  • 10. Native method implementation jstring ← Java return type Java_jni_CHelloWorld_hello( JNIEnv* env, jobject thiz ) Naming convention for JNI functions “this” object reference Pointer to JNI environment for JNI functions access
  • 11. Method overloading package jni; public class CHelloWorld { native String hello(); native String hello(String what, int count); . . . }
  • 12. Method overloading /* * Class: jni_CHelloWorld * Method: hello * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_jni_CHelloWorld_hello__ (JNIEnv *, jobject); /* * Class: jni_CHelloWorld * Method: hello * Signature: (Ljava/lang/String;I)Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_jni_CHelloWorld_hello__Ljava_lang_String_2I (JNIEnv *, jobject, jstring, jint);
  • 13. Resolving method names A native method name is concatenated from the following components: • the prefix Java_ • a mangled fully-qualified class name • an underscore (“_”) separator • a mangled method name • for overloaded native methods, two underscores (“__”) followed by the mangled argument signature
  • 14. javah tool The javah command conveniently generates C header and source files that are needed to implement native methods. (Generated files not really required) $ javah -d .srcnative -cp .binjava jni.CHelloWorld
  • 15. JNI native function arguments The JNI interface pointer is the first argument to native methods. The JNI interface pointer is of type JNIEnv. The second argument differs depending on whether the native method is static or nonstatic. • The second argument to a nonstatic native method is a reference to the object. • The second argument to a static native method is a reference to its Java class.
  • 16. JNI native function arguments The remaining arguments correspond to regular Java method arguments. The native method call passes its result back to the calling routine via the return value
  • 17. JNIEvn* Reference to JNI environment, which lets you access all the JNI functions. Used for: Create new objects Access Fields inside Java classes Invoke Java Methods. It points to the thread’s local data, so it cannot be shared between threads.
  • 18. Note on C++ #include <jni.h> extern ”C” { jstring Java_jni_CHelloWorld_hello(JNIEnv *env, jobject thiz) { return env->NewStringUTF("hello, world (from JNI)"); } }
  • 19. Arguments of a primitive type passed by value Java Type Native Type Constants boolean jboolean JNI_FALSE, JNI_TRUE byte jbyte char jchar short jshort int jint long jlong float jfloat double jdouble void void jsize scalar values and sizes
  • 20. Reference types Reference types passed “by reference”. Here is native method hierarchy:
  • 21. Accessing Strings jstring Java_jni_CHelloWorld_hello__Ljava_lang_String_2I (JNIEnv* env, jobject thiz, jstring what, jint count) { char dest[30]; /* Obtain string characters */ const char* str = (*env)->GetStringUTFChars(env, what, 0); strcpy(dest, “hello, “); strncat(dest, str, 22); /* Relase characters to avoid memory leak */ (*env)->ReleaseStringUTFChars(env, what, str); return (*env)->NewStringUTF(env, dest); }
  • 22. Local and Global References • Every argument passed to JNI call is a local reference that is valid only for the duration of the call. This applies to all sub-classes of jobject, including jclass, jstring, and jarray. • In order to get Global references: jobject NewGlobalRef(JNIEnv *env, jobject obj); • Global reference is live until it is not explicitly released void DeleteGlobalRef(JNIEnv *env, jobject globalRef);
  • 23. Local and Global References • Do "not excessively allocate" local references. • Free local references them manually with DeleteLocalRef() • The implementation is only required to reserve slots for 16 local references, • if you need more than that you should either delete as you go or use EnsureLocalCapacity/PushLocalFrame to reserve more
  • 24. Passing array arguments /* private native long sumAll(int[] numbers); */ jlong Java_jni_CHelloWorld_sumAll(JNIEnv *env, jobject thiz, jintArray values_) { jint *values = (*env)->GetIntArrayElements(env, values_, NULL); jsize len = (*env)->GetArrayLength(env, values_); jlong sum = 0; int i; for (i = 0; i < len; i++) { sum += values[i]; } (*env)->ReleaseIntArrayElements(env, values_, values, 0); return sum; }
  • 25. On class file structure Goal: read or write class or instance variables from the JNI code Goal: call java methods from the JNI code Java VM type signatures: Z boolean B byte C char S short I int J long F float D double Lfully-qualified-class; fully-qualified-class [type type[] (arg-types)ret-type method type
  • 26. VM Signature example Example Java method signature long foo(int n, String s, int[] arr); JVM Type signature: (ILjava/lang/String;[I)J
  • 27.
  • 28. javap tool javap is Java Class File disassembler tool that comes to rescue $ javap -s -p -cp .binjava jni.CHelloWorld
  • 29. Accessing class/instance members Find correct class object Find member index, either method or field Use correct instance object Do method invocation or field access
  • 30. Non-static method invocation - Find class of your object jclass cl = (*env)->GetObjectClass(env, textView); - Find method jmethodID methodId = (*env)->GetMethodID(env, cl, "setText", "(Ljava/lang/CharSequence;)V"); - Call your method using correct JNI function (*env)->CallVoidMethod(env, textView, methodId, … );
  • 31. Static method invocation - Find correct class if needed jclass cl = FindClass(env, "java/lang/String"); - Find static method jmethodID methodId = (*env)->GetStaticMethodID(env, cl, "copyValueOf", "([C)Ljava/lang/String;"); - Call using correct invocation method jobject o = (*env)->CallStaticObjectMethod(env, cl, methodId, /* NativeTypes */ … );
  • 32. Accessing instance fields - Find object’s class - Get field id jfieldID fieldId = (*env)->GetFieldID(env, clazz, "chars", "[C"); - Get/set field value using correct method jobject o = (*env)->GetObjectField(env, instance, jfieldID ); (*env)->SetObjectField(env, instance, jfieldId, /* NativeType */ value);
  • 33. Accessing static fields - Find correct class if needed - Find static field jfieldID fieldId = (*env)->GetStaticFieldID(env, clazz, "count", "I"); - Get/set static field value using correct method jint i = (*env)->GetStaticIntField(env, instance, jfieldID ); (*env)->SetStaticIntField(env, instance, jfieldId, /* NativeType */ 5);
  • 34. Checking for errors Calling most of JNI functions is not allowed if exception is pending and will cause crash. When there is a chance on an exception JNI must check for the exception state jboolean ExceptionCheck(JNIEnv *env); jthrowable ExceptionOccurred(JNIEnv *env); void ExceptionClear(JNIEnv *env); void ExceptionDescribe(JNIEnv *env);
  • 35. Throwing an exception jint Throw(JNIEnv *env, jthrowable obj); jint ThrowNew(JNIEnv *env, jclass clazz, const char *message); void FatalError(JNIEnv *env, const char *msg);