Java Reference
In-Depth Information
makes the call and then implement the native method in C
++
.Tobecallable by
the JVM, that C
code must be written in a very specific way with a very specific
signature, about which we learn in this example. To complete this example, we
need the following:
aJava class that calls the native method
a native method implementation in the proper form
aruntime-loadable library containing the native method
++
The native method must reside in a library that can be loaded at runtime by
the JVM. For Linux/Unix operating systems, the library must be a shared object
library (typically with the . so filename extension). For Windows, the library must
be a Windows DLL ( .dll extension). We need to know how to write the native
method and how to create the shared library in such a way that the JVM can load
the library and call the method. The Java class that calls the native method looks
much like any other Java class except for two additions: it must declare the native
methods it uses as native , and it must load the library that contains the native
code.
The Java source code that calls a native method looks just like source code
that calls any other method, but when the JVM routes that native call to the native
implementation, the JVM requires a very specific native function signature - i.e.
the function name, the list of parameters and types, and the return type. You
must know that signature in order to properly implement the native method in
the native language. The signature is derived from the native method declaration
in the calling Java class using a very specific set of rules. We describe those
rules here but do so through examples rather than a boring listing of the rules.
After you have used JNI for a while, you will understand those rules and should
be able to derive the native language signature simply by inspecting the native
method declaration in the Java source file. For beginners, rather than memorizing
and applying the rules, it is far easier to use a tool that generates the required
signature. The Java 2 SDK includes the javah tool that generates a C-style
header file from a compiled Java class that contains native method declarations.
Therefore the steps to create and run a JNI application are:
1. Create a Java class that declares the native method and loads the native library that
contains the native implementation.
2. Compile the Java source file.
3. Run the javah tool to generate a header file for the native method.
4. Create an implementation of the native method using the generated header file.
5. Compile the native implementation.
6. Create a shared object library containing the native implementation.
7. Run the Java class.
These steps must be performed in the order shown. The following sections demon-
strate how to perform each step for the simple Hello World example.
Search WWH ::




Custom Search