13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5.7 Going Native133Example 5.7 Java applicati<strong>on</strong> with a native method (GetUser.java)public class GetUser {static {System.loadLibrary("getuser");}public native String getUserName();public static void main(String[] args){GetUser usr = new GetUser();}}System.out.println(usr.getUserName());is called a static initializer and we’ll discuss it in a moment.Once you have the Java code, compile it with javac. You now have thecompiled class. The next step is to use the javah tool to build the header filefor your C code.$ javah GetUserExample 5.8 shows the header file thus produced.Note that you run javah <strong>on</strong> the class file, not <strong>on</strong> the source file. The normalclass name to classpath mappings apply. The file produced as a result iscalled, in this case, GetUser.h. The next step is to write the C code thatimplements the method (Example 5.9).There’s a lot going <strong>on</strong> here. First, the c<strong>on</strong>stant, L_cuserid, is defined instdio.h; it represents the number of characters required to hold a user name.We’re defining a char array to hold that number of characters plus <strong>on</strong>e. 10 Weare then calling the cuserid() functi<strong>on</strong> (see the manpage of cuserid(3)) toget the user name of the effective user ID of the process.That much is familiar C. But what is the argument list? Our method tookno arguments. And what’s with the functi<strong>on</strong>s being called through the pointerargument?10. What can we say? We’re paranoid about the trailing null. Sue us.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!