Java Reference
In-Depth Information
can sometimes run faster than Java, though this is becoming less important. Like everything
else in Java, the “native code” mechanism is subject to security restrictions; for example, ap-
plets are not allowed to access native code.
The native code language bindings are defined for code written in C or C++. If you need to
access a language other than C/C++, write a bit of C/C++ and have it pass control to other
functions or applications, using any mechanism defined by your operating system.
Due to such system-dependent features as the interpretation of header files and the allocation
of the processor's general-purpose registers, your native code may need to be compiled by
the same C compiler used to compile the Java runtime for your platform. For example, on
Solaris you can use SunPro C or maybe gcc. On Win32 platforms, use Microsoft visual C++
Version 4.x or higher (32 bit). For Linux and Mac OS X, you should be able to use the
provided gcc-based compiler. For other platforms, see your Java vendor's documentation.
Also note that the details in this section are for the Java Native Interface (JNI) of Java 1.1
and later, which differs in some details from 1.0 and from Microsoft's native interface.
IAN'S BASIC STEPS: JAVA CALLING NATIVE CODE
To call native code from Java:
1. Write Java code that calls a native method.
2. Compile this Java code.
3. Create an .h file using javah .
4. Write a C function that does the work.
5. Compile the C code into a loadable object.
6. Try it!
The first step is to write Java code that calls a native method. To do this, use the keyword
native to indicate that the method is native, and provide a static code block that loads your
native method using System.loadLibrary() . (The dynamically loadable module is created
in Step 5.) Static blocks are executed when the class containing them is loaded; loading the
native code here ensures it is in memory when needed!
Search WWH ::




Custom Search