Although Java is easy to transfer platforms, we still need some C++/C libraries to control drivers or basic modules.
JNI can be an interface between Java and C++/C.
The following article will teach you step by step.
OS: Ubuntu 18.04
Java: Open JDK 8
Step 1. Implement Java: HelloWorldJNI.java
class HelloWorldJNI {
private native void printByC();
public static void main(String[] args) {
new HelloWorldJNI().printByC();
}
static {
System.setProperty("java.library.path", "~/Desktop/JNI/");
System.loadLibrary("HelloWorldJNI");
}
}
Step 2. Generate Class and Header
(open your terminal)
$ javac HelloWorldJNI.java
$ javah -jni HelloWorldJNI
Then HelloWorldJNI.class and HelloWorldJNI.h are created.
HelloWorldJNI.h:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorldJNI */
#ifndef _Included_HelloWorldJNI
#define _Included_HelloWorldJNI
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: HelloWorldJNI
* Method: printByC
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_HelloWorldJNI_printByC
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Step 3. Implement your C++/C library: HelloWorldJNI.c
#include <jni.h>
#include <stdio.h>
#include "HelloWorldJNI.h"
JNIEXPORT void JNICALL Java_HelloWorldJNI_printByC (JNIEnv *env, jobject obj){
printf("Hello from C\n");
return;
}
Step 4. Build C++/C library as .so
(open your terminal)
$ gcc -shared -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux HelloWorldJNI.c -o libHelloWorldJNI.so
The name ,”lib“+name.so, is important because the definition of “System.loadLibrary” will recognize “lib”.
Step 5. Test
(open your terminal)
$ java HelloWorldJNI
OUTPUT:
$ Hello from C