Extra exercise 12: Java Native Interface

  1. Review content of jtm.extra12 package and src/main/c/jnifunctions.c file.
  2. Install GNU C compiler:

    sudo apt-get install gcc
  3. Implement TODO's for JNIClass.java class and jnifunctions.c file.
  4. Compile JNIClass.java file considering classpath and target location:

    javac -cp target/classes -d target/classes src/main/java/jtm/extra12/JNIClass.java
  5. Generate jtm_extra12_JNIClass.h file in lib folder:

    javah -cp target/classes -d lib/ jtm.extra12.JNIClass

    This file will be located in lib folder of the project.

  6. Check that list of methods is generated in jtm_extra12_JNIClass.h file.
  7. Implement generated interfaces from lib/jtm_extra12_JNIClass.h file in /src/main/c/jnifunctions.c file:

    JNIEXPORT void JNICALL Java_jtm_extra12_JNIClass_printHello(JNIEnv * env, jclass class) {
    // TODO call printHello();

    JNIEXPORT void JNICALL Java_jtm_extra12_JNIClass_printArray
    (JNIEnv * env, jobject obj, jstring string) {
            // TODO #1: convert jstring to array of C chars
            // TODO #2: call printArray(yourarray);
            // TODO #3: release resourches for passed jstring

    JNIEXPORT jstring JNICALL Java_jtm_extra12_JNIClass_createArray(JNIEnv * env,
    jobject obj, jint size) {
            // TODO #1: call createArray(size);
            // TODO #2: convert created array of C chars to jstring
            // TODO #3: return jstring
  8. Compile jnifunctions.c file including JNI libraries for 64-bit Linux:

    gcc -fPIC -I/usr/lib/jvm/java-8-openjdk-amd64/include \
    -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux \
    ./src/main/c/jnifunctions.c -c -o ./lib/jnifunctions.o
  9. Make shared library for Linux:

    gcc -shared ./lib/jnifunctions.o -o ./lib/jnifunctions.so
  10. Test application by calling its main() method:

    java -cp target/classes/ jtm.extra12.JNIClass
  11. Ensure JNIClassTest1.java unit tests are passing.

Optional tasks

  1. You can compile jnifunctions.c as executable with following parameters:

    gcc -I/usr/lib/jvm/java-8-openjdk-amd64/include \
    -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux \
    ./src/main/c/jnifunctions.c -o ./lib/hello.o
  2. Then execute created binary by:



Created by Valdis Vītoliņš on 2018-03-28 14:24
Last modified by Valdis Vītoliņš on 2019-05-31 16:23
Xwiki Powered
Creative Commons Attribution 3.0 Unported License