Java Native Interface
suggest changeVersions
JNI has been in Java SE since 1.1. The original version list ran through Java SE 9 Early Access.
Parameters
| Parameter | Details |
|---|---|
JNIEnv |
Pointer to the JNI environment |
jobject |
The object which invoked the non-static native method |
jclass |
The class which invoked the static native method |
Remarks
Setting up JNI requires both a Java and a native compiler. Depending on the IDE and OS, there is some setting up required. A guide for Eclipse can be found here. A full tutorial can be found here.
These are the steps for setting up the Java-C++ linkage on Windows:
- Compile the Java source files (
.java) into classes (.class) usingjavac. - Create header (
.h) files from the Java classes containingnativemethods usingjavah. These files “instruct” the native code which methods it is responsible for implementing. JDK 10 removedjavah;javac -hwrites the same headers. - Include the header files (
#include) in the C++ source files (.cpp) implementing thenativemethods. - Compile the C++ source files and create a library (
.dll). This library contains the native code implementation. - Pass the library directory with
-Djava.library.pathwhen starting the JVM, and load the library from Java withSystem.loadLibrary(...). That option is not written into the source file.
Calling Java methods from native code requires a method descriptor. If the descriptor is incorrect, a runtime error occurs. javap -s prints the descriptors.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents