SlideShare a Scribd company logo
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
Getting started with the JNI
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

PPTX
Basics of Object Oriented Programming in Python
PPTX
Object oriented programming in python
PPTX
Object oriented programming with python
PPT
Java tutorials
PPT
PDF
Object oriented approach in python programming
PPT
Object Oriented Programming with Java
PDF
Java Programming - 04 object oriented in java
Basics of Object Oriented Programming in Python
Object oriented programming in python
Object oriented programming with python
Java tutorials
Object oriented approach in python programming
Object Oriented Programming with Java
Java Programming - 04 object oriented in java

What's hot (19)

PPTX
Java Notes
PDF
201005 accelerometer and core Location
PPTX
Class, object and inheritance in python
ODP
Synapseindia reviews.odp.
PPTX
About Python
PPT
Introduction to-programming
PPT
Java Tutorial
PDF
Java Programming - 05 access control in java
PPTX
Access modifiers in java
PPT
Java basic tutorial by sanjeevini india
PPTX
Python oop third class
PPTX
CLASS OBJECT AND INHERITANCE IN PYTHON
PPTX
Object Oriented Programming in Python
PPT
Core Java Programming | Data Type | operator | java Control Flow| Class 2
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PDF
Object.__class__.__dict__ - python object model and friends - with examples
PPTX
Object oreinted php | OOPs
PDF
Chapter 01 Introduction to Java by Tushar B Kute
PPT
Core java
Java Notes
201005 accelerometer and core Location
Class, object and inheritance in python
Synapseindia reviews.odp.
About Python
Introduction to-programming
Java Tutorial
Java Programming - 05 access control in java
Access modifiers in java
Java basic tutorial by sanjeevini india
Python oop third class
CLASS OBJECT AND INHERITANCE IN PYTHON
Object Oriented Programming in Python
Core Java Programming | Data Type | operator | java Control Flow| Class 2
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Object.__class__.__dict__ - python object model and friends - with examples
Object oreinted php | OOPs
Chapter 01 Introduction to Java by Tushar B Kute
Core java
Ad

Viewers also liked (20)

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

Similar to Getting started with the JNI (20)

PDF
NDK Primer (AnDevCon Boston 2014)
PDF
NDK Primer (Wearable DevCon 2014)
PPT
Android JNI
PDF
JNI - Java & C in the same project
PPT
C++ programming with jni
PDF
JNA - Let's C what it's worth
PPTX
Let's talk about jni
PDF
109842496 jni
PDF
Using the Android Native Development Kit (NDK)
PDF
Android and cpp
PPTX
JNI 使用淺談
PDF
Introduction to the Android NDK
PPTX
GOTO Night with Charles Nutter Slides
PDF
Proceedings Of The 2002 Acm Sigplan Haskell Workshop Haskell 02 Pittsburgh Pe...
PDF
JNI - Java & C in the same project
PPTX
Android ndk
PPTX
Native development kit (ndk) introduction
PDF
Using the Android Native Development Kit (NDK)
PDF
Native code in Android applications
PPTX
Using the android ndk - DroidCon Paris 2014
NDK Primer (AnDevCon Boston 2014)
NDK Primer (Wearable DevCon 2014)
Android JNI
JNI - Java & C in the same project
C++ programming with jni
JNA - Let's C what it's worth
Let's talk about jni
109842496 jni
Using the Android Native Development Kit (NDK)
Android and cpp
JNI 使用淺談
Introduction to the Android NDK
GOTO Night with Charles Nutter Slides
Proceedings Of The 2002 Acm Sigplan Haskell Workshop Haskell 02 Pittsburgh Pe...
JNI - Java & C in the same project
Android ndk
Native development kit (ndk) introduction
Using the Android Native Development Kit (NDK)
Native code in Android applications
Using the android ndk - DroidCon Paris 2014

Recently uploaded (20)

PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
ai tools demonstartion for schools and inter college
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
top salesforce developer skills in 2025.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
System and Network Administraation Chapter 3
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
AI in Product Development-omnex systems
PDF
Nekopoi APK 2025 free lastest update
PDF
System and Network Administration Chapter 2
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Navsoft: AI-Powered Business Solutions & Custom Software Development
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
ai tools demonstartion for schools and inter college
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Reimagine Home Health with the Power of Agentic AI​
Operating system designcfffgfgggggggvggggggggg
top salesforce developer skills in 2025.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
System and Network Administraation Chapter 3
Odoo Companies in India – Driving Business Transformation.pdf
How to Choose the Right IT Partner for Your Business in Malaysia
VVF-Customer-Presentation2025-Ver1.9.pptx
Upgrade and Innovation Strategies for SAP ERP Customers
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
AI in Product Development-omnex systems
Nekopoi APK 2025 free lastest update
System and Network Administration Chapter 2
PTS Company Brochure 2025 (1).pdf.......
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool

Getting started with the 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
  • 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);