After a long break I am posting a simple tutorial on JNI which is one of my favourites.
JNI is Java Native Interface, which we can use to call the native methods written in languages other than Java. We are going to call a method written in C++. JNI is very useful where you cannot use Java such as getting system hardware information and much more, it depends up on what you need.
For this tutorial you need to read my old post on creating a simple dll in VC++, though if you know how to create DLL's using VC++ then you can skip that post.
Lets get started with our tutorial..
First step is to write a class which will use JNI.
Well its too simple, following is the code for our Java class which will be using JNI
After writing this Java class you need to compile this Java class so we will get class file - JNITest.class
Now we will generate header file i.e. JNITest.h for writing C++ function for it, for that you use following command which will generate JNITest.h in same folder
After you create your DLL put this DLL in same directory where the class is and that's it.
Run your Java program
JNI is Java Native Interface, which we can use to call the native methods written in languages other than Java. We are going to call a method written in C++. JNI is very useful where you cannot use Java such as getting system hardware information and much more, it depends up on what you need.
For this tutorial you need to read my old post on creating a simple dll in VC++, though if you know how to create DLL's using VC++ then you can skip that post.
Lets get started with our tutorial..
First step is to write a class which will use JNI.
Well its too simple, following is the code for our Java class which will be using JNI
import java.io.*; class JNITest {
// native method public native static void WinMessage(String str); static { System.loadLibrary("SimpleDll"); } public static void main(String args[]) { WinMessage("Hello From JNI"); } }
After writing this Java class you need to compile this Java class so we will get class file - JNITest.class
Now we will generate header file i.e. JNITest.h for writing C++ function for it, for that you use following command which will generate JNITest.h in same folder
javah JNITestThis will generate header file for using C++ function. Open this file see the function prototype generated, now you have to write this function in your library, of course including this header file in your project. How to write DLL file in VC++ I have already posted one article for it, read it if you don't know how to write DLL.
After you create your DLL put this DLL in same directory where the class is and that's it.
Run your Java program
java JNITestyou will see the result
Comments
Post a Comment