JNI short tutorial

Create a Java class to use code in C

1 Write a Java class that uses C codes

public class CraftJNI {
  static {
    System.loadLibrary("hello"); // Load native library hello.dll (windows)
                                 // or libhello.so (Unixes) at runtime.
                                 // This library contains a native method sayHello()
  // Declare an instance native method sayHello() which receives no parameter
  // returns void
  private native void sayHello();
  // Test Driver
  public static void main(String[] args) {
    new CraftJNI().sayHello(); // Create an instance and invoke native method

2 Compile Java program CraftJNI.java

javac -h . CraftJNI.java
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class CraftJNI */

#ifndef _Included_CraftJNI
#define _Included_CraftJNI
#ifdef __cplusplus
extern "C" {
 * Class:     CraftJNI
 * Method:    sayHello
 * Signature: ()V
JNIEXPORT void JNICALL Java_CraftJNI_sayHello
  (JNIEnv *, jobject);

#ifdef __cplusplus

To know more about the generated class file

javap -verbose CraftJNI.class

3 Implement C program

#include <jni.h>   // Standard JDK provided header
#include <stdio.h> // Standard C IO header
#include <CraftJNI.h> // Generated header

JNIEXPORT void JNICALL Java_CraftJNI_sayHello(JNIEnv *env, jobject thisObj) {
  printf("I am in C code \n");

4 Compile C program

gcc -fPIC -I"." -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" \
   -shared -o libhello.so CraftJNI.c
> java -Djava.library.path=. CraftJNI
I am in C code


Error 1: class file has wrong version

> javah CraftJNI.class
Error: cannot access CraftJNI
  bad class file: ./CraftJNI.class
    class file has wrong version 55.0, should be 52.0

Reason: javah is not available with Java 11

> java -version
openjdk version "" 2020-11-04
OpenJDK Runtime Environment (build
OpenJDK 64-Bit Server VM (build, mixed mode, sharing)

> javac -version

> javah -version
javah version "1.8.0_252"

> whereis java
java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz

> ls /usr/share/man/man1 | grep java*

Error 2:

> java -Djava.library.path=. CraftJNI
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello in java.library.path: [.]
        at java.base/java.lang.ClassLoader.loadLibrary(ClassLoader.java:2670)
        at java.base/java.lang.Runtime.loadLibrary0(Runtime.java:830)
        at java.base/java.lang.System.loadLibrary(System.java:1873)
        at CraftJNI.<clinit>(CraftJNI.java:4)


Last updated