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
CraftJNI.javaTo know more about the generated class file
3 Implement C program
4 Compile C program
Troubleshooting
Error 1: class file has wrong version
Reason: javah is not available with Java 11
Error 2:
References
JNI reference docs - https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jniTOC.html
Some of the code is shamelessly copied from https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
Last updated
Was this helpful?