Java Native Interface (JNI)

Java supports native codes via the Java Native Interface (JNI).
1. JNI with C

1.1: Write a Java Class that uses C Codes – hello.java 1
1.2: Create the C/C++ Header file – hello.h 2
1.3: C Implementation – HelloJNI.c 2
1.4: Run the Java Program 3

1.  JNI with C

 

1.1: Write a Java Class that uses C Codes – hello.java

The static initializer invokes System.loadLibrary() to load the native library “hello” (which contains the native method sayHello()) during the class loading. It will be mapped to “libhello.so“. You could include the library into Java Library’s path via JVM argument -Djava.library.path=path_to_lib.
Next, we declare the method sayHello() as a native instance method, via keyword native, which denotes that this method is implemented in another language. A native method does not contain a body. The sayHello() is contained in the native library loaded.
The main() method allocate an instance of hello and invoke the native method sayHello().
Compile the “hello.java” into “hello.class”.

1.2: Create the C/C++ Header file – hello.h

(get .h)

 

 

1.3: C Implementation – HelloJNI.c

 

(get .o)

(get .so)

1.4: Run the Java Program

 

 

LInk