Steps of using Java Native Interface (Call C/C++ methods from Java)
-
Create a Java Project
-
Create a class named Hello.java
-
Write the head of method contains native keyword that describe the functions/methods in C++ (like this)
-
Compile the Hello.java class using the IDE or by typing this command in the folder that's contain the class:
javac Hello.java
Note: If javac is not recognized, you need to add the JDK path to the "system environment variable"
-
Generate the C/C++ JNI header by typing this command:
javah Hello
And you will see the Hello.h file generated (like this)
-
Create new project of type Dynamic Link Library on the CodeBlocks IDE
-
Import the Hello.h file
-
Create new file named Hello.cpp and make the implementation of the Hello.h method (like this)
-
Add the jni.h support to C++ compiler:
-
Right click on the project and click to Build Options
-
Go to Other compiler options
-
Add this two lines:
-I"<JDK path>\include" -I"<JDK path>\include\win32"
In my case:
-I"C:\Program Files\Java\jdk1.8.0_231\include" -I"C:\Program Files\Java\jdk1.8.0_231\include\win32"
-
-
Build the project
- From C++ project go to the bin\Debug folder and copy the generated library (something like *.dll) and paste it in the java project for example under src/cpplib folder
- Now, go to the Hello.java class and import the library using the System.loadLibrary method (see this example here)
- Create Main method, call the native java method & run the App
If this tutorial helps you, please ⭐ this repo and share it with others