Extra exercise 12: Java Native Interface

  1. To add support for C development in Eclipse, install Eclipse CDT plugin, which you can search in Eclipse Marketplace by entering cdt.
  2. Review content of jtm.extra12 package and src/main/c/jnifunctions.c file.
  3. Install GNU C compiler:

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

    javac -cp target/classes -d target/classes src/main/java/jtm/extra12/JNIClass.java
  6. 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.

  7. Check that list of methods is generated in jtm_extra12_JNIClass.h file.
  8. 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
  9. 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
  10. Make shared library for Linux:

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

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

Optional tasks

  1. You can compile jnifunctions.c as independent 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-08-16 12:04
Xwiki Powered
Creative Commons Attribution 3.0 Unported License