Java Reference
In-Depth Information
library in a static initializer ensures that the library is available when needed.)
Alternatively, one could load the library later, as long as it is loaded before the
first call to a native method is encountered. For this example, the library could be
loaded at the beginning of main() , just before calling nativeHelloWorld-
Static() .However, System.loadLibrary() is most commonly seen in a
static initializer.
The parameter passed to System.loadLibrary() is the shared library
name, which must correspond to the name of the actual shared library that contains
the native code. System.loadLibrary() performs the same function on all
platforms, but the way in which it does that function is platform-specific. In partic-
ular, the name provided is converted to a platform-specific standard shared library
name. On a Solaris or Linux system, the input name NativeHelloWorld is
converted to a library named libNativeHelloWorld.so ,while a Windows
system converts the same input name to NativeHelloWorld.dll . Capital-
ization is preserved in the name conversion on all platforms, which is important
to keep note of on a case-sensitive operating system but doesn't really matter on
aWindows system.
22.3.2 Compile the Java source file
The compilation of the source file above is simple:
javac -classpath build/classes -d build/classes
src/javatech/jni22/JNIHelloWorld.java
As in some previous examples, we separate the generated . class files from the
source files by using a build/classes directory.
22.3.3 Generate the header file
In order to implement the method in a native language, a header file for that native
language method is required. As described above, the header gives us the function
signature for the native implementation. Because it does a bit more than just that,
the header file must be included ( #include )inCorC
++
implementations.
The Java 2 SDK supplies the javah tool to generate the C header file from a
compiled Java class file.
The name of the header file is formed from the fully qualified class name
of the class on which it is based. As with other tools, the -d switch directs the
output to a named directory. Since it is generated output, rather than source code
that we write, we put the output into a headers subdirectory below the build
directory:
javah -classpath build/classes -jni -d build/headers
javatech.jni22.JNIHelloWorld
Search WWH ::




Custom Search