Extra 12. Java Native Interface
Main steps
- To add support for C development in Eclipse, install Eclipse CDT plugin, which you can search in Eclipse Marketplace by entering cdt.
- Review content of jtm.extra12 package and src/main/c/jnifunctions.c file.
Install GNU C compiler:
sudo apt-get update
sudo apt-get install gcc- Implement TODO's for JNIClass.java class and jnifunctions.c file.
Compile JNIClass.java file considering classpath and target location:
javac -cp target/classes -d target/classes src/main/java/jtm/extra12/JNIClass.javaGenerate jtm_extra12_JNIClass.h file in lib folder:
javac -cp target/classes -h lib/ src/main/java/jtm/extra12/JNIClass.javaThis file will be located in lib folder of the project.
- Check that list of methods is generated in jtm_extra12_JNIClass.h file.
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
}Compile jnifunctions.c file including JNI libraries for 64-bit Linux:
gcc -fPIC -I/usr/lib/jvm/java-11-openjdk-amd64/include \
-I/usr/lib/jvm/java-11-openjdk-amd64/include/linux \
./src/main/c/jnifunctions.c -c -o ./lib/jnifunctions.oMake shared library for Linux:
gcc -shared ./lib/jnifunctions.o -o ./lib/jnifunctions.soTest application by calling its main() method:
java -cp target/classes/ jtm.extra12.JNIClass- Ensure JNIClassTest1.java unit tests are passing.
Optional tasks
You can compile jnifunctions.c as independent executable with following parameters:
gcc -I/usr/lib/jvm/java-11-openjdk-amd64/include \
-I/usr/lib/jvm/java-11-openjdk-amd64/include/linux \
./src/main/c/jnifunctions.c -o ./lib/hello.oThen execute created binary by:
./lib/hello.o