Native Access

The preferred mechanism for accessing native functionality on Mac OS X is the standard Java Native Interface (JNI). This section builds a simple JNI library using Apple’s Project Builder tool, found in /Developer/Applications/.

Tip

In the past, Apple supplied a technology known as JDirect, a set of bindings between native code and Java that is much simpler than JNI. Specifically, JDirect allows access to native libraries without the cumbersome header generation of JNI. Apple has deprecated JDirect, however, and strongly encourages the use of JNI. In fact, the latest versions of the JDK (1.4+) remove JDirect altogether.

To begin, launch Project Builder and select “File New Project.” Select the “Java Java JNI Application” option, as shown in Figure 5-3. On the next panel, name your project and give it a location (here, we’ll name it “JNIExample”). Then save it in ~/JNIExample/.

JNI’s new project

Figure 5-3. JNI’s new project

The assistant will generate several files for you automatically, as shown in Figure 5-4. Before looking at the files, however, consider the build process and the targets, as shown in Figure 5-5. When building applications with JNI, you should usually first write Java application code, and then flag methods that will have a native implementation using the native keyword:

            native boolean loginAsRoot(String username, String password);

Figure 5-4. JNI files

Figure 5-5. JNI ...

Get Mac OS X for Java Geeks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.