Calling C Code from Java
Volume Number: 13
Issue Number: 9
Column Tag: Java Workshop
by Andrew Downs
Using native code with Java applications and the Sun JDK
This article shows how to access C code (also called native code) from within Java code.
The C code exists as a PowerPC shared library containing several Process Manager
calls. The functions in the shared library are used to get and store process
information. A Java front-end calls the shared library at specified intervals to
retrieve and display the process information. Timing for these calls is accomplished
using a thread. The front-end also includes a preferences dialog with a pseudo-custom
control written in Java. This program runs as a Java application, not an applet.
This article assumes you are familiar with both Java and the Macintosh Toolbox. The
Java portion of this program was developed using the Sun Java Development Kit (JDK)
version 1.0.2. The native code is written in C. CodeWarrior 9 is used to build a
PowerPC shared library from the C code.
Why Native Code?
One of Java's strengths is that it often insulates the programmer from the specifics of
the users' platform. Sometimes, however, you need access to information that cannot
be retrieved using one of the existing Java packages.
Fortunately, Java allows you to call non-Java code, usually referred to as native code.
Using the Sun JDK v1.0.2 on the Macintosh, this native code must exist as a PowerPC
shared library. If you have access to one of the non-Java integrated development
environments, creating such a library is available as a project option. Refer to your
development environment information for details. This article will use CodeWarrior to
create a shared library. A sample CodeWarrior project for this purpose is also
included with the JDK.
Briefly, here are the steps in the overall development process:
1. Write and compile the Java code that makes the call to a native method. If
the file is called .java, the generated code will be contained in