Let’s talk
about JNI
Yongqiang Li
Agenda
 JNI Overview
 JNI Sample Step by Step
 More Details of JNI
 JVM Native Memory
 Reference
JNI (Java Native Interface)
Overview
                   Linux C/C++ Side


 Java Side
                   Windows C/C++ Side
(Code, VM)


                   Mac OS C/C++ Side
Java –verbose:jni HelloWorld
JNI Sample (Step 1)
 Define
       the Java class
 and native functions
Step 2
 Use “javah” to
 generate the header
 for native functions.
Header File
Step 3
 Implement   .c/.cpp
Step 4
 Build   the native code
     g++ -I/usr/lib/java/include –
      I/usr/lib/java/include/linux -share
      org_yli_jni_SampleJNI.cpp -o libNative.so
Step 5
 Run   it!
    java -Djava.library.path=. SampleJNI
A Real Case – Use Java to
start GTK+ application.
More Details of JNI
 JNI   Type
JNIEnv
 Definea set of functions to manipulate
 JNI data, get field/method id, find class.
    env->GetVersion()
    env->Throw()
    env->FindClass()
    env->NewLocalRef()
a   Thread Local Storage variable
Fields
 Can’t    access
  directly
 Need to get Field
  ID first
Methods
 Method ID is
 needed, just like
 fields.
Use “javap” to find out the signature.
And Constructor
 Use   GetMethodID as well
 But method name is special. It’s “<init>”.
 Still use “javap” to find out its signature.
 Need use env->NewObject() to create a
  new instance.
 As   well, jstring can’t be manipulated directly.

       jstring

• Depends on JNIEnv Functions
   •   GetStringChars/GetStringUTFChars
   •   ReleaseStringChars/ReleaseStringUTFChars
   •   GetStringLength/GetStringUTFLength
   •   NewString/NewStringUTF
Other things depends on
JNIEnv
 Manage   Reference
 Find Class
 Access Array
 Throw exception
…
Native Memory
Consume native memory
More topics…
 Launch  JVM in C/C++
 Traps and pitfalls
Reference
 Java Native Interface Specification
 Thanks for the memory
Let's talk about jni

Let's talk about jni