|
|
Step By Step |
In this step, you use thejavahutility program to generate a header file (a.hfile) from theHelloWorldJava class. The header file defines a structure that represents theHelloWorldclass on the native language side, and provides a function definition for the implementation of the native methoddisplayHelloWorld()defined in that class.Run
javahnow on theHelloWorldclass that you created in the previous steps.By default,
javahplaces the new.hfile in the same directory as the.classfile. You can telljavahto place the header files in a different directory with the-doption.The name of the header file is the Java class name with a
.happended to the end of it. For example, the command shown above will generate a file namedHelloWorld.h.The Class Structure
Look at the header fileHelloWorld.h.Notice that it contains a#includejava example/HelloWorld.hstructdefinition for a structure namedClassHelloWorld. The members of this structure parallel the members of the corresponding Java class; that is to say, the fields in thestructcorrespond to instance variables in the class. But sinceHelloWorlddoesn't have any instance variables, there is just a place holder in the structure. You can use the members of thestructto reference class instance variables from your native language functions.Also, notice that the header file contains this line:
This creates aHandleTo(HelloWorld);typedef structnamedHHelloWorld, which you use to pass objects between Java and another language.The Function Definition
In addition to the structure that mimics the Java class, you will also notice a function signature that looks like this:This is the definition for the function that you will write in Step 5: Write the Native Method Implementation that provides the implementation for theextern void HelloWorld_displayHelloWorld(struct HHelloWorld *);HelloWorldclass's native methoddisplayHelloWorld(). You must use this function signature when you write the implementation for the native method. IfHelloWorldcontained any other native methods, their function signatures would appear here as well.The name of the native language function that implements the native method is derived from the package name, the class name, and the name of the Java native method. Thus, the native method
displayHelloWorld()within theHelloWorldclass becomesHelloWorld_displayHelloWorld(). In our example, there is no package name becauseHelloWorldis in the default package.You will notice that the native language function accepts a single parameter even though the native method defined in the Java class accepts none. You can think of the parameter as the "this" variable in C++. Our example ignores the "this" parameter. The next lesson, Implementing Native Methods
, describes how to access the data in the "this" parameter.
|
|
Step By Step |