SlideShare a Scribd company logo
1 of 46
Download to read offline
JNI
Karol Wrótniak
• Java Native Interface
• Native:
• Platform-specific shared library (.dll, .so, .dylib)
• Non-hybrid mobile app, React Native
• C, C++
• Call native functions from Java and vice versa
• Other JVM languages supported
• JNI ≠ JNA
Overview
• Implement operations not achievable in pure Java:
• System clock - System.currentTimeMillis()
• Filesystem access
• Sockets (e.g. for HTTP requests)
• Reuse existing native libraries
• Hinder reverse-engineering
• Increase performance (in certain cases only):
• computation
Why JNI?
Sample projects using JNI
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
static {
System.loadLibrary("foo");
}
public native int getTextLength(String text);
#include <jni.h>
JNIEXPORT
jint
JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength(
JNIEnv *env,
jobject thiz,
jstring text
) {
return (*env)->GetStringUTFLength(env, text);
}
foo.c:
Foo.java:
• System.loadLibrary("foo")
• System.mapLibraryName("foo") ➔ "libfoo.so"
• java.library.path property
• System.load("/usr/local/lib/libfoo.so")
Java API
• jbyte, jchar, jshort, jint, jlong, jfloat, jdouble
• jboolean: JNI_TRUE, JNI_FALSE
• jstring, jthrowable
• jarray, jintarray...
• jclass, jobject
• jmethodID, jfieldID
JNI types
Calling Java from C
jclass mathClass = (*env)->FindClass(env, "java/lang/Math");
jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass,
"min", "(JJ)J");
jlong min = (*env)->CallStaticLongMethod(env, mathClass,
minMethodID, x, y);
public static long min(long a, long b)
Calling Java from C
jclass mathClass = (*env)->FindClass(env, "java/lang/Math");
jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass,
"min", "(JJ)J");
jlong min = (*env)->CallStaticLongMethod(env, mathClass,
minMethodID, x, y);
public static long min(long a, long b)
Calling Java from C
jclass mathClass = (*env)->FindClass(env, "java/lang/Math");
jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass,
"min", "(JJ)J");
jlong min = (*env)->CallStaticLongMethod(env, mathClass,
minMethodID, x, y);
public static long min(long a, long b)
Calling Java methods
jclass mathClass = (*env)->FindClass(env, "java/lang/Math");
jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass,
"min", "(JJ)J");
jlong min = (*env)->CallStaticLongMethod(env, mathClass,
minMethodID, x, y);
public static long min(long a, long b)
Accessing Java fields
jobject calendar = …
jclass calendar_class = (*env)->GetObjectClass(env, calendar);
jfieldID time_field_id = (*env)->GetFieldID(env, calendar_class,
"time", "J");
jlong time = (*env)->GetLongField(env, calendar, time_field_id);
Creating Java objects
jclass foo_class = (*env)->FindClass(env,
"pl/droidsonroids/ndkdemo/Foo");
jmethodID constructor_id = (*env)->GetMethodID(env, foo_class,
"<init>", "()V");
jobject foo = (*env)->NewObject(env, foo_class, constructor_id);
Type signatures
Type signature Java type Example
Z boolean
B byte
C char
S short
I int
J long
F float
D double
L<FQCN>; FQCN Lcom/foo/Foo;
[<type> type[] [Z
V void
javap -s <class file>
abstract ArrayList<String> foo(String[] a, boolean b);
([Ljava/lang/String;Z)Ljava/util/ArrayList;
• Local
• Global
• WeakGlobal (weaker than Java Weak and Soft)
Reference types
Local references
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(
JNIEnv *env,
jobject thiz,
jobject foo
) {
//...
}
Local reference
Global References
jobject persistent_foo;
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(
JNIEnv *env,
jobject thiz,
jobject foo
) {
persistent_foo = (*env)->NewGlobalRef(env, foo);
}
(*env)->DeleteGlobalRef(env, persistent_foo);
Finalizers
public final class Foo {
@Override
protected void finalize() throws Throwable {
releaseBar(bar);
super.finalize();
}
private final long bar;
public Foo() {
bar = createBar();
}
private native long createBar();
private native void releaseBar(long bar);
...
JNI_OnLoad JNI_OnUnload
void *foo;
JavaVM *global_vm;
JNIEXPORT
jint JNI_OnLoad(JavaVM *vm, void *reserved) {
global_vm = vm;
foo = malloc(1024);
if (foo == NULL) {
return JNI_ERR;
}
return JNI_VERSION_1_8;
}
JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) {
free(foo);
}
Registering native methods
//Foo.java
public native int plus(int a, int b);
//Foo.c
static jint add(JNIEnv *env, jobject thiz, jint a, jint b) {
return a + b;
}
JNIEXPORT
jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
JNINativeMethod methods[] = {
{"plus", "(II)I", (void *) add}
};
return JNI_VERSION_1_6;
}
Registering native methods
//Foo.java
public native int plus(int a, int b);
//Foo.c
static jint add(JNIEnv *env, jobject thiz, jint a, jint b) {
return a + b;
}
JNIEXPORT
jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
JNINativeMethod methods[] = {
{"plus", "(II)I", (void *) add}
};
JNIEnv *env;
(*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6);
jclass foo_class = (*env)->FindClass(env,
"pl/droidsonroids/ndkdemo/Foo");
(*env)->RegisterNatives(env, foo_class, methods, 1);
return JNI_VERSION_1_6;
}
Registering native methods
//Foo.java
public native int plus(int a, int b);
//Foo.c
static jint add(JNIEnv *env, jobject thiz, jint a, jint b) {
return a + b;
}
• JNI functions:
• ExceptionCheck
• ExceptionOccured
• ExceptionClear
• FatalError
• ExceptionDescribe
Handling exceptions
(*env)->CallVoidMethod(env, foo, fooMethodID);
if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
(*env)->ExceptionClear(env);
(*env)->CallVoidMethod(env, foo, barMethodID);
}
Catching exceptions
catch
• Need to clear exception or return before JNI calls
Arrays
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz,
jintArray points) {
jsize length = (*env)->GetArrayLength(env, points);
jint *native_points = (*env)->GetIntArrayElements(env, points,
NULL);
//...
(*env)->ReleaseIntArrayElements(env, points, native_points, 0);
}
Arrays
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz,
jintArray points) {
jsize length = (*env)->GetArrayLength(env, points);
jint *native_points = (*env)->GetIntArrayElements(env, points,
NULL);
//...
(*env)->ReleaseIntArrayElements(env, points, native_points, 0);
}
Arrays
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz,
jintArray points) {
jsize length = (*env)->GetArrayLength(env, points);
jint *native_points = (*env)->GetIntArrayElements(env, points,
NULL);
//...
(*env)->ReleaseIntArrayElements(env, points, native_points, 0);
}
Release mode
Arrays
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz,
jintArray points) {
jsize length = (*env)->GetArrayLength(env, points);
jint *native_points = (*env)->GetIntArrayElements(env, points,
NULL);
//...
(*env)->ReleaseIntArrayElements(env, points, native_points, 0);
}
*isCopy
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray
points) {
jsize start = 0;
jsize size = 2;
jint native_points[2];
(*env)->GetIntArrayRegion(env, points, start, size, native_points);
native_points[0] = native_points[1];
(*env)->SetIntArrayRegion(env, points, start, size, native_points);
}
Arrays
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz,
jintArray points) {
jsize length = (*env)->GetArrayLength(env, points);
jint *native_points = (*env)->GetIntArrayElements(env, points,
NULL);
//...
(*env)->ReleaseIntArrayElements(env, points, native_points, 0);
}
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray
points) {
jsize start = 0;
jsize size = 2;
jint native_points[2];
(*env)->GetIntArrayRegion(env, points, start, size, native_points);
native_points[0] = native_points[1];
(*env)->SetIntArrayRegion(env, points, start, size, native_points);
}
Arrays
JNIEXPORT void JNICALL
Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz,
jintArray points) {
jsize length = (*env)->GetArrayLength(env, points);
jint *native_points = (*env)->GetIntArrayElements(env, points,
NULL);
//...
(*env)->ReleaseIntArrayElements(env, points, native_points, 0);
}
GC compaction
• Disable GC between Get and Release
• Pin
• Copy
Java heap
native heap
Mode Copy back Free buffer
0 ✓ ✓
JNI_COMMIT ✓ ❌
JNI_ABORT ❌ ✓
Release modes & isCopy
Need to release with another mode
*isCopy == JNI_FALSE:
• skip useless commit
• restore original contents before abort
Direct byte buffers
ByteBuffer.allocateDirect(1024);
void *foo = (*env)->GetDirectBufferAddress(env, buffer);
jlong capacity = (*env)->GetDirectBufferCapacity(env, buffer);
1. Java Native Interface Specification
2. JNI Tips
3. The Java™ Native Interface
Programmer’s Guide and Specification
References
Q&A
Android dev @DroidsOnRoids
Co-organizer @GDG Wrocław
karol.wrotniak@droidsonroids.pl
koral--
Karol Wrótniak
karol-wrotniak
@karol.wrotniak

More Related Content

What's hot

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingAnton Arhipov
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1PyCon Italia
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)Simon Su
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispDamien Cassou
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheeltcurdt
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptjeffz
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)jeffz
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancementup2soul
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 

What's hot (20)

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1Cleanup and new optimizations in WPython 1.1
Cleanup and new optimizations in WPython 1.1
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)JCConf 2015  - 輕鬆學google的雲端開發 - Google App Engine入門(上)
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
 
Metaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common LispMetaprogramming and Reflection in Common Lisp
Metaprogramming and Reflection in Common Lisp
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)Jscex: Write Sexy JavaScript (中文)
Jscex: Write Sexy JavaScript (中文)
 
Planet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance EnhancementPlanet-HTML5-Game-Engine Javascript Performance Enhancement
Planet-HTML5-Game-Engine Javascript Performance Enhancement
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 

Similar to JNI - Java & C in the same project

JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 
Supercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicSupercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicIan Robertson
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015Charles Nutter
 
Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 xshyamx
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)Gandhi Ravi
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on AndroidSven Haiges
 
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
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 

Similar to JNI - Java & C in the same project (20)

Android ndk
Android ndkAndroid ndk
Android ndk
 
Android and cpp
Android and cppAndroid and cpp
Android and cpp
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
Supercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamicSupercharging reflective libraries with InvokeDynamic
Supercharging reflective libraries with InvokeDynamic
 
JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
Dynamic C#
Dynamic C# Dynamic C#
Dynamic C#
 
Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8 Why is Java relevant? New features of Java8
Why is Java relevant? New features of Java8
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Node intro
Node introNode intro
Node intro
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
CouchDB on Android
CouchDB on AndroidCouchDB on Android
CouchDB on Android
 
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)
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Json generation
Json generationJson generation
Json generation
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 

Recently uploaded

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 

Recently uploaded (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

JNI - Java & C in the same project

  • 2. • Java Native Interface • Native: • Platform-specific shared library (.dll, .so, .dylib) • Non-hybrid mobile app, React Native • C, C++ • Call native functions from Java and vice versa • Other JVM languages supported • JNI ≠ JNA Overview
  • 3. • Implement operations not achievable in pure Java: • System clock - System.currentTimeMillis() • Filesystem access • Sockets (e.g. for HTTP requests) • Reuse existing native libraries • Hinder reverse-engineering • Increase performance (in certain cases only): • computation Why JNI?
  • 5. static { System.loadLibrary("foo"); } public native int getTextLength(String text); Foo.java:
  • 6. static { System.loadLibrary("foo"); } public native int getTextLength(String text); Foo.java:
  • 7. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 8. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 9. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 10. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 11. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 12. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 13. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 14. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 15. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 16. static { System.loadLibrary("foo"); } public native int getTextLength(String text); #include <jni.h> JNIEXPORT jint JNICALL Java_pl_droidsonroids_ndkdemo_Foo_getTextLength( JNIEnv *env, jobject thiz, jstring text ) { return (*env)->GetStringUTFLength(env, text); } foo.c: Foo.java:
  • 17. • System.loadLibrary("foo") • System.mapLibraryName("foo") ➔ "libfoo.so" • java.library.path property • System.load("/usr/local/lib/libfoo.so") Java API
  • 18. • jbyte, jchar, jshort, jint, jlong, jfloat, jdouble • jboolean: JNI_TRUE, JNI_FALSE • jstring, jthrowable • jarray, jintarray... • jclass, jobject • jmethodID, jfieldID JNI types
  • 19. Calling Java from C jclass mathClass = (*env)->FindClass(env, "java/lang/Math"); jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass, "min", "(JJ)J"); jlong min = (*env)->CallStaticLongMethod(env, mathClass, minMethodID, x, y); public static long min(long a, long b)
  • 20. Calling Java from C jclass mathClass = (*env)->FindClass(env, "java/lang/Math"); jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass, "min", "(JJ)J"); jlong min = (*env)->CallStaticLongMethod(env, mathClass, minMethodID, x, y); public static long min(long a, long b)
  • 21. Calling Java from C jclass mathClass = (*env)->FindClass(env, "java/lang/Math"); jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass, "min", "(JJ)J"); jlong min = (*env)->CallStaticLongMethod(env, mathClass, minMethodID, x, y); public static long min(long a, long b)
  • 22. Calling Java methods jclass mathClass = (*env)->FindClass(env, "java/lang/Math"); jmethodID minMethodID = (*env)->GetStaticMethodID(env, mathClass, "min", "(JJ)J"); jlong min = (*env)->CallStaticLongMethod(env, mathClass, minMethodID, x, y); public static long min(long a, long b)
  • 23. Accessing Java fields jobject calendar = … jclass calendar_class = (*env)->GetObjectClass(env, calendar); jfieldID time_field_id = (*env)->GetFieldID(env, calendar_class, "time", "J"); jlong time = (*env)->GetLongField(env, calendar, time_field_id);
  • 24. Creating Java objects jclass foo_class = (*env)->FindClass(env, "pl/droidsonroids/ndkdemo/Foo"); jmethodID constructor_id = (*env)->GetMethodID(env, foo_class, "<init>", "()V"); jobject foo = (*env)->NewObject(env, foo_class, constructor_id);
  • 25. Type signatures Type signature Java type Example Z boolean B byte C char S short I int J long F float D double L<FQCN>; FQCN Lcom/foo/Foo; [<type> type[] [Z V void javap -s <class file> abstract ArrayList<String> foo(String[] a, boolean b); ([Ljava/lang/String;Z)Ljava/util/ArrayList;
  • 26. • Local • Global • WeakGlobal (weaker than Java Weak and Soft) Reference types
  • 27. Local references JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo( JNIEnv *env, jobject thiz, jobject foo ) { //... } Local reference
  • 28. Global References jobject persistent_foo; JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo( JNIEnv *env, jobject thiz, jobject foo ) { persistent_foo = (*env)->NewGlobalRef(env, foo); } (*env)->DeleteGlobalRef(env, persistent_foo);
  • 29. Finalizers public final class Foo { @Override protected void finalize() throws Throwable { releaseBar(bar); super.finalize(); } private final long bar; public Foo() { bar = createBar(); } private native long createBar(); private native void releaseBar(long bar); ...
  • 30. JNI_OnLoad JNI_OnUnload void *foo; JavaVM *global_vm; JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { global_vm = vm; foo = malloc(1024); if (foo == NULL) { return JNI_ERR; } return JNI_VERSION_1_8; } JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) { free(foo); }
  • 31. Registering native methods //Foo.java public native int plus(int a, int b); //Foo.c static jint add(JNIEnv *env, jobject thiz, jint a, jint b) { return a + b; }
  • 32. JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNINativeMethod methods[] = { {"plus", "(II)I", (void *) add} }; return JNI_VERSION_1_6; } Registering native methods //Foo.java public native int plus(int a, int b); //Foo.c static jint add(JNIEnv *env, jobject thiz, jint a, jint b) { return a + b; }
  • 33. JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { JNINativeMethod methods[] = { {"plus", "(II)I", (void *) add} }; JNIEnv *env; (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); jclass foo_class = (*env)->FindClass(env, "pl/droidsonroids/ndkdemo/Foo"); (*env)->RegisterNatives(env, foo_class, methods, 1); return JNI_VERSION_1_6; } Registering native methods //Foo.java public native int plus(int a, int b); //Foo.c static jint add(JNIEnv *env, jobject thiz, jint a, jint b) { return a + b; }
  • 34. • JNI functions: • ExceptionCheck • ExceptionOccured • ExceptionClear • FatalError • ExceptionDescribe Handling exceptions
  • 35. (*env)->CallVoidMethod(env, foo, fooMethodID); if ((*env)->ExceptionCheck(env) == JNI_TRUE) { (*env)->ExceptionClear(env); (*env)->CallVoidMethod(env, foo, barMethodID); } Catching exceptions catch • Need to clear exception or return before JNI calls
  • 36. Arrays JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize length = (*env)->GetArrayLength(env, points); jint *native_points = (*env)->GetIntArrayElements(env, points, NULL); //... (*env)->ReleaseIntArrayElements(env, points, native_points, 0); }
  • 37. Arrays JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize length = (*env)->GetArrayLength(env, points); jint *native_points = (*env)->GetIntArrayElements(env, points, NULL); //... (*env)->ReleaseIntArrayElements(env, points, native_points, 0); }
  • 38. Arrays JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize length = (*env)->GetArrayLength(env, points); jint *native_points = (*env)->GetIntArrayElements(env, points, NULL); //... (*env)->ReleaseIntArrayElements(env, points, native_points, 0); } Release mode
  • 39. Arrays JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize length = (*env)->GetArrayLength(env, points); jint *native_points = (*env)->GetIntArrayElements(env, points, NULL); //... (*env)->ReleaseIntArrayElements(env, points, native_points, 0); } *isCopy
  • 40. JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize start = 0; jsize size = 2; jint native_points[2]; (*env)->GetIntArrayRegion(env, points, start, size, native_points); native_points[0] = native_points[1]; (*env)->SetIntArrayRegion(env, points, start, size, native_points); } Arrays JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize length = (*env)->GetArrayLength(env, points); jint *native_points = (*env)->GetIntArrayElements(env, points, NULL); //... (*env)->ReleaseIntArrayElements(env, points, native_points, 0); }
  • 41. JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize start = 0; jsize size = 2; jint native_points[2]; (*env)->GetIntArrayRegion(env, points, start, size, native_points); native_points[0] = native_points[1]; (*env)->SetIntArrayRegion(env, points, start, size, native_points); } Arrays JNIEXPORT void JNICALL Java_pl_droidsonroids_ndkdemo_Foo_foo(JNIEnv *env, jobject thiz, jintArray points) { jsize length = (*env)->GetArrayLength(env, points); jint *native_points = (*env)->GetIntArrayElements(env, points, NULL); //... (*env)->ReleaseIntArrayElements(env, points, native_points, 0); }
  • 42. GC compaction • Disable GC between Get and Release • Pin • Copy Java heap native heap
  • 43. Mode Copy back Free buffer 0 ✓ ✓ JNI_COMMIT ✓ ❌ JNI_ABORT ❌ ✓ Release modes & isCopy Need to release with another mode *isCopy == JNI_FALSE: • skip useless commit • restore original contents before abort
  • 44. Direct byte buffers ByteBuffer.allocateDirect(1024); void *foo = (*env)->GetDirectBufferAddress(env, buffer); jlong capacity = (*env)->GetDirectBufferCapacity(env, buffer);
  • 45. 1. Java Native Interface Specification 2. JNI Tips 3. The Java™ Native Interface Programmer’s Guide and Specification References
  • 46. Q&A Android dev @DroidsOnRoids Co-organizer @GDG Wrocław karol.wrotniak@droidsonroids.pl koral-- Karol Wrótniak karol-wrotniak @karol.wrotniak