Java Reference
In-Depth Information
5.7
G OING N ATIVE
Now we come to the deeper darker mysteries. Let us take a look at javah . No,
javah is not a Hebrew word. It is not some lost mystical text from the days be-
fore science supplanted magic. It is the Java C header and stub file generator.
If you are not already fairly experienced in writing, compiling, and build-
ing shared libraries in C on a Linux system, we would suggest that you skip this
section, at least until you have developed intermediate skills in these areas.
Otherwise, feel free to proceed.
We're going to walk you very quickly through building a Java native
method here. 9 Don't worry if you don't quite follow it all. We will cover this
topic at greater length elsewhere in the topic. For now, we're giving you the
highlights. Also be sure to check out Section 5.15. We'll point you to many
additional resources on JNI (Java Native Interface) in that section.
Sounds pretty intimidating, huh? Well, depending upon your background
and experience, it can be a bit intimidating. As much as this will hurt some die-
hard Java purists, Java is not the right language for everything. Java's size and
semiinterpreted nature in particular make Java ill-suited for the “close to the
metal” tasks, such as device drivers and raw socket networking.
Fortunately, Java's designers were of this rocket-scientist breed (and so,
for that matter, are your bending authors), so they gave Java programmers a
back door: native methods . A native method is a class method whose name, ar-
guments, and return type are declared in Java, but whose underlying implemen-
tation is written in “native code” (usually C, but it could be any compiled
language that can match C's stack frame conventions).
As an example, let's implement a native method that will use the native
Linux C library calls to get the current program's effective user ID and the
name associated with that user.
First, we will write the Java class (Example 5.7).
You may never have seen code like that at the start of a class definition.
The block declared
static { ... }
9. You might be tempted to call our comments in the introduction where we mentioned that
we did not like purely pedagogical examples and that we would provide real, useful code. Well,
we have to confess that there are some features of the Java language that we couldn't cram into
our real-world examples. This JNI sample is one such. We admit our failure, and we apologize.
Search WWH ::




Custom Search