For an example consider that we are creating a java project named “HelloWorldJNI” which has the following structure and location.
Class Name: HelloWorldJNI
Structure:
HelloWorldJNI
\src
\bin
.settings
.classpath
.project
Package:
test.HelloWorld
Location:
C:\workspace\HelloWorldJNI
Steps in the JNI programming
Step #1: JNI requires the native methods to be declared in java as,public class HelloWorld{Step #2: compile the class using jdk’s javac compiler as follows,
public native void displayHelloWorld();
static{
System.loadLibrary("HelloWorldDLL");
}
}
C:\workspace\HelloWorldJNI>javac.exe src\test\HelloWorld.javaStep #3: Using jdk’s javah.exe create the header file in C/C++ code by invoking following command from the command prompt.
C:\workspace\HelloWorldJNI>javah -jni -o src\test\HelloWorld.h -classpath C:\workspace\HelloWorldJNI\src test.HelloWorldhere “–o” will define the output file name where “–classpath” will define the working path and “test.HelloWorld” will give the input file name.Step #4: create a Win32 DLL in C/C++ named HelloWorldDLL and copy the DLL file to the C:\workspace\HelloWorldJNI\src location.
Step #5: create a main method in test.TestApp class in java as follows,
public class TestApp{Step #6: in the command prompt run the program as
public static vois main(String[] arg){
HelloWorld hd = new HelloWorld();
hd.displayHelloWorld();
}
}
C:\workspace\HelloWorldJNI>java HelloWorldJNIThis entire process is illustrated in the following diagram which was taken from the The JNI Programmer’s Guide. Finally the result will be displayed in the command prompt as “Hello World!” as shown in the below diagram.
A complete JNI learning experience can be gained through going through The Java Native Interface Programmer’s Guide and Specification. Hope this article helped you to do a simple Hello World application correctly which has a packaging structure.
No comments:
Post a Comment