--- tags: Java,JNI --- # JAVA JNI How To Use ## Introduce JNI is an interface that allows java to interact with code wrriten in another language. ### JNI Componets **javah** is a JDK tool that generate C-style header file from a given Java class that include native methods. **jni.h** is a c/c++ header file included with the JDK that maps JAVA types to their native counterparts. ``` boolean jboolean byte jbyte char jchar double jdouble float jfloat int jint long jlong short jshort void void ``` ### JNI Development - Java Part 1. Create a Java class with native method `public native void sayHi();` 2. Load the library which implements the method: System.loadLibrary("Hello"); 3. Invoke the native method from Java Code. ``` public class Hello { public native void sayHi(); public static void main(String []args) { new Hello().sayHi(); } static{ System.loadLibrary("Hello"); } } ``` The method *sayHi* will be implemented in C/C++ in separate files, which will be compiled into a library. The library filename will be called *libHello.so* (on Unix) or *Hello.dll* (on Windows), but when loaded in Java, the library has to be loaded as *Hello* ### JNI Development - C Part 1. Use the JDK javah utility to generate the header file *Hello.h* with a function prototype for *sayHi* method. ``` $ javac Hello.java $ javah -jni Hello $ ls Hello.class Hello.h Hello.java ``` 2. Create *Hello.c* to implement the *sayHi* function The file *Hello.h* looks like Code. ``` $ cat Hello.h /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class Hello */ #ifndef _Included_Hello #define _Included_Hello #ifdef __cplusplus extern "C" { #endif /* * Class: Hello * Method: sayHi * Signature: ()V */ JNIEXPORT void JNICALL Java_Hello_sayHi (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif ``` The file *Hello.c* look like: Code. ``` #include <stdio.h> #include "Hello.h" JNIEXPORT void JNICALL Java_Hello_sayHi (JNIEnv *env, jobject object) { printf("Hi\n"); } ``` ### Compiling Compiling *Hello.c* to generate libHello.so ``` $ gcc -o libHello.so -fPIC -lc -shared \ -I/usr/lib/jvm/java-8-openjdk-amd64/include \ -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux \ Hello.c ``` Set *LD_LIBRARY_PATH* to point to directory where the compiled library is stored. Run your Java application. Code. ``` $ export LD_LIBRARY_PATH=. $ java Hello Hi ```