Hope you all are having great time with your LOVE (JAVA :P )
Well we all have read about JNI i.e. Java Native Interface.
What is JNI?
Well JNI is a programming framework that allows Java to execute applications specific to a hardware or an Operating System Platform written in various languages: C,C++ or assembly
Now we all know what is JNI, but
HOW TO IMPLEMENT IT?
I am providing u steps with screenshot to make it easy to understand and implement
But before you begin coding your 1st code using JNI we have to install 2 things
- SDK (includes JDK and JRE)
- Microsoft Visual C++
Steps To implement HelloWorld code using JNI
1. Create a normal java file but include a native method in your code. Sample code is given below
2. Now save this code HelloWorld.java and compile it using CMD/Terminal
javac HelloWorld.java
3. After successful (NOTE: javac HelloWorld.java executed without any error) we have to execute this command in CMD/Terminal itself
javah -jni HelloWorld
After this execution you will have 3 files -> HelloWorld.java, HelloWorld.class and HelloWorld.h
4. Now open HelloWorld.h file. The file will be as follows
5. Now this HelloWorld.h file is generated automatically. We will edit this code so that this HelloWorld.h can perform some operation.
To do this we have to define the method
Java_HelloWorld_sayHello(JNIEnv *,jobject,jstring)
Here is the modified code
6. Now we require DLL file that can be embedded in our HelloWorld.java file
We use Microsost Visula C++ command-line tool. Before that rename HelloWorld.h to HelloWorld.c and then
type the below command to get the dll file
cl -c /I<your jdk path>\include /I<your jdk path>\include\win32 HelloWorld.c link /libpath=<your jdk path>\lib HelloWorld.obj /dll
Eg:
cl -c /Ic:\jdk1.1.6\include /Ic:\jdk1.1.6\include\win32 HelloWorld.c
cl -c /Ic:\jdk1.1.6\include /Ic:\jdk1.1.6\include\win32 HelloWorld.c
link /libpath=c:\jdk1.1.6\lib HelloWorld.obj /dll
7. Now comes modification of the HelloWorld.java file. Modified code is given below
8. Congrats you completed your 1st JNI HelloWorld code
Now to execute your code
compile the HelloWorld.java code again and execute it using command java HelloWorld ( NOTE: These commands are executed in your terminal/CMD)
OUTPUT: Hello
Sorry currently i m not having Microsoft Visual C++ so cant show you the dll file and final execution
Congrats you just learned to create your own code using JNI :)
Take Care
Peace
For Any Query mail me: ravjot.singh.28@gmail.com
No comments:
Post a Comment