|
|
Compiling and Running a Java Program with a Native Method |
In this step, you use thejavahutility program to generate a header file (a.hfile) from theHelloWorldclass. The header file provides a C function signature for the implementation of the native methoddisplayHelloWorlddefined in that class.Run
javahnow on theHelloWorldclass that you created in the previous steps.The name of the header file is the Java class name with a
.happended to the end. For example, the command shown above will generate a file namedHelloWorld.h.By default,
javahplaces the new.hfile in the same directory as the.classfile. Use the-doption to instructjavahto place the header files in a different directory.The Function Definition
Look at the header fileHelloWorld.h.The#includejava example-1dot1/HelloWorld.hJava_HelloWorld_displayHelloWorldfunction provides the implementation for theHelloWorldclass's native methoddisplayHelloWorld, which you will write in Step 4: Write the Native Method Implementation. You use the same function signature when you write the implementation for the native method.If
HelloWorldcontained any other native methods, their function signatures would appear here as well.The name of the native language function that implements the native method consists of the prefix
Java_, the package name, the class name, and the name of the native method. Between each name component is an underscore "_" separator. Graphically, this looks as follows:The native method
displayHelloWorldwithin theHelloWorldclass becomesJava_HelloWorld_displayHelloWorld. No package name appears in our example becauseHelloWorldis in the default package, which has no name.Notice that the implementation of the native function, as it appears in the header file, accepts two parameters even though, in its definition on the Java side, it accepts no parameters. The JNI requires every native method to have these two parameters.
The first parameter for every native method is a
JNIEnvinterface pointer. It is through this pointer that your native code accesses parameters and objects passed to it from the Java application. The second parameter isjobject, which references the current object itself. In a sense, you can think of thejobjectparameter as the "this" variable in Java. For a native instance method, such as thedisplayHelloWorldmethod in our example, thejobjectargument is a reference to the current instance of the object. For native class methods, this argument would be a reference to the method's Java class. Our example ignores both parameters. The next lesson, Integrating Java and Native Programs, describes how to access data using the JNI interface pointer
envparameter. The next lesson also provides more information aboutjobject.
|
|
Compiling and Running a Java Program with a Native Method |