Page 1 of 1

JNI Java Native Interface

Posted: Thu Apr 16, 2015 9:01 pm
by fabiodelorenzo
Create a new JAVA project in eclipse
Create a new class NewJniTest in package com.crokky.test like this:

Code: Select all

package com.crokky.test;

public class NewJniTest {

   static {
      System.loadLibrary("JNITest");
   }

   // Declare a native methods
   private native void myFunction();

   public static void main(String[] args) {
      NewJniTest j = new NewJniTest();
      j.myFunction();
   }
}


build the java file (either from Eclipse or with the java command)
now, from the root of the project (with src and bin sub directories) create the .h file from the class file:

Code: Select all

cd bin
javah -jni com.crokky.test.NewJniTest

com.crokky.test is the package and NewJniTest is the class name.
this will create the header file com_crokky_test_NewJniTest.h that we should deploy with the src java code so
the java developer will know the available APIs of the native library

Then, from any other directory, create your C file:

Code: Select all

#include <jni.h>
#include <stdio.h>

JNIEXPORT void JNICALL Java_com_crokky_test_NewJniTest_myFunction(JNIEnv *env, jobject thisObj) {
   printf("Fabio is here !\n");
   return;
}


Carefull with: Java_com_crokky_test_NewJniTest_myFunction
The naming convention for C function is Java_{package_name}_{classname}_{functionname}(JNI arguments).

Then, let's build the C code:

Code: Select all

gcc -Wall -I"$JAVA_HOME/include" -fPIC -shared -o libJNITest.so JNITest.c

check that your JAVA_HOME is pointing to the right directory.
Mine is:
JAVA_HOME="/usr/lib/jvm/java-7-openjdk-amd64"
FYI:
ls /usr/lib/jvm/java-7-openjdk-amd64
ASSEMBLY_EXCEPTION bin docs include jre lib man src.zip THIRD_PARTY_README

Now, we should have libJNITest.so.
Copy this file in the libs directory of your eclipse project.
If the directory is not there, create it.

Now we have to tell Eclipse to use our library:
look ath the java code:

Code: Select all

      System.loadLibrary("JNITest");

but the real library name is: libJNITest.so

Refresh the eclipse project (F5)
Right click on the eclipse project and select [properties].
Select the Libraries tab
Open the JRE System Library
Select Native library location
Select workspace
and select the libs directory in your project

Done ! Enjoy and as usual, if you have any question drop me an email at fabio@crokky.com