JNI short tutorial
Create a Java class to use code in C

1 Write a Java class that uses C codes

CraftJNI.java
1
public class CraftJNI {
2
static {
3
System.loadLibrary("hello"); // Load native library hello.dll (windows)
4
// or libhello.so (Unixes) at runtime.
5
// This library contains a native method sayHello()
6
7
}
8
9
// Declare an instance native method sayHello() which receives no parameter
10
// returns void
11
private native void sayHello();
12
13
// Test Driver
14
public static void main(String[] args) {
15
new CraftJNI().sayHello(); // Create an instance and invoke native method
16
}
17
}
Copied!

2 Compile Java program CraftJNI.java

1
javac -h . CraftJNI.java
Copied!
CraftJNI.h
1
/* DO NOT EDIT THIS FILE - it is machine generated */
2
#include <jni.h>
3
/* Header for class CraftJNI */
4
5
#ifndef _Included_CraftJNI
6
#define _Included_CraftJNI
7
#ifdef __cplusplus
8
extern "C" {
9
#endif
10
/*
11
* Class: CraftJNI
12
* Method: sayHello
13
* Signature: ()V
14
*/
15
JNIEXPORT void JNICALL Java_CraftJNI_sayHello
16
(JNIEnv *, jobject);
17
18
#ifdef __cplusplus
19
}
20
#endif
21
#endif
Copied!
To know more about the generated class file
1
javap -verbose CraftJNI.class
Copied!

3 Implement C program

CraftJNI.c
1
#include <jni.h> // Standard JDK provided header
2
#include <stdio.h> // Standard C IO header
3
#include <CraftJNI.h> // Generated header
4
5
JNIEXPORT void JNICALL Java_CraftJNI_sayHello(JNIEnv *env, jobject thisObj) {
6
printf("I am in C code \n");
7
return;
8
}
9
Copied!

4 Compile C program

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

Troubleshooting

Error 1: class file has wrong version

1
> javah CraftJNI.class
2
Error: cannot access CraftJNI
3
bad class file: ./CraftJNI.class
4
class file has wrong version 55.0, should be 52.0
Copied!
Reason: javah is not available with Java 11
1
> java -version
2
openjdk version "11.0.9.1" 2020-11-04
3
OpenJDK Runtime Environment (build 11.0.9.1+1-post-Debian-1deb10u2)
4
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-post-Debian-1deb10u2, mixed mode, sharing)
5
6
> javac -version
7
javac 11.0.9.1
8
9
> javah -version
10
javah version "1.8.0_252"
11
12
> whereis java
13
java: /usr/bin/java /usr/share/java /usr/share/man/man1/java.1.gz
14
15
> ls /usr/share/man/man1 | grep java*
16
java.1.gz
17
javac.1.gz
18
javadoc.1.gz
19
javah.1.gz
20
javap.1.gz
Copied!

Error 2:

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

References

Last modified 8mo ago
Copy link