TweetFollow Us on Twitter

Calling C Code from Java

Volume Number: 13 (1997)
Issue Number: 9
Column Tag: Java Workshop

Calling C Code from Java

by Andrew Downs

Using native code with Java applications and the Sun JDK

Introduction

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 <native>.java, the generated code will be contained in <native>.class.
  2. Drop the <native>class file onto the JavaH application (included with the JDK), which will generate the header and stub files.
  3. Move the <native>.h and <native>.stub files into the folder with your native code.
  4. Build the native library in CodeWarrior, using <native>.c as the source file.
  5. Move the native library (or an alias to it) to one of two places: the JavaSoft Folder in the Extensions folder, or the folder containing the Java front-end. (These locations are mapped into the classpath by Java Runner, so it can find any supporting code.)
  6. Write and compile the Java code for the front-end.
  7. Drop the .class file containing your application's main() method onto the Sun Java Runner application to run it.

Before we begin, let's take a closer look at shared libraries and what should be put in them.

What's in a Shared Library?

A shared library consists of functions that may be called by one or more applications (or other types of code, including other libraries). The shared library functions do not run as standalone code. Rather, the shared library provides its services to applications that know how to call its member functions. Shared library code exists in a separate file from the code fragment or fragments that comprise the application.

When creating a PowerPC shared library, the function code gets compiled into the data fork of the library file. The data fork acts as a container for the compiled code. (Multiple containers may exist in the data fork, but we won't deal with that issue here.) A code fragment resource (of type 'cfrg') with an ID of 0 (zero) is placed in the resource fork of the library file. This resource contains information about where in the data fork the library code begins, as well as what architecture the code adheres to (in this case, PowerPC).

The shared library must be loaded into memory before use. This may be done when the client application starts up, or as requested by the application. Our Java code relies on the latter approach: one of the classes contains a call to load and prepare the library at a specific time during program execution. The Process Manager (which handles the launching and running of applications) relies on the services of the Code Fragment Manager to prepare the library code for execution. (For more information on the Code Fragment Manager, refer to Inside Macintosh: PowerPC System Software.)

You will see that the source code for our shared library does not resemble a typical Macintosh application. It has no event loop, and does not initialize any of the Toolbox managers. Instead, the functions in our shared library rely on the client application to set up any managers that may be required.

The current version of the JDK does not contain any packages or classes that let you peek at the currently running processes on the system. That will be the purpose of our shared library: to obtain and provide process information to our Java front-end program.

Getting the process information into the shared library is easy. A function in the shared library calls the appropriate Process Manager routines, and saves the data they return.

We need a way to get this process information from the shared library to our Java program. We accomplish this using a Java class containing definitions of native methods. (The word "native" is a modifier in Java which may be used in method declarations. It indicates that the body of the method is defined elsewhere, and is not Java code.) These native methods are really calls to C functions in the shared library. We will treat them like accessor methods: each is responsible for one action, such as returning to the caller a specific piece of data. One of them instructs the shared library to read a new set of process information. Another returns the number of current processes. A third returns the partition size of a specific process, and so on.

Setting up the Shared Library

At this point, we know that we have to create a shared library containing C code, and that the functions in this library will be called using native methods in a Java class. We determined that the functions will return specific pieces of data. We can now design the shared library in more detail.

The Process Manager information we need includes the name, partition size, and current RAM in use by each process. Once we get the information, we store it in a (global) array of structs. Each struct contains the data for one process. To get at the data, we will walk through the array, checking each element in turn. We can setup the header file for our C code as follows:

Listing 1: ProcessWatcher.h

ProcessWatcher.h
The header file for ProcessWatcher.c.

/**************************
  ProcessWatcher.h
**************************/
//  Define some macros to make our code more readable.
#define  NIL                0L
#define  ONE_KBYTE_SIZE      1024
#define  DIFFERENCE_FACTOR    16
#define  MAX_NUM_RECORDS      20
#define  STRING_LENGTH        32

//  Define a struct that holds the information we want for
//  one process. Then create an array of these structs. 
struct appStruct
{
  Str32  processName;
  long    processSize;
  long    currentSize;
}  ;

struct    appStruct  gArray[ MAX_NUM_RECORDS ];

//  One global variable as an array counter.
short    gNumRecords;

//  Our function prototypes.
long    DoGetNumRecords( void );
long    DoGetCurrentSize( long i );
long    DoGetProcessSize( long i );
long    DoGetProcessNameLength( long i );
long    DoGetProcessNameChar( long i, long j );
void    DoGetProcessInfo( void );

The first five function prototypes listed above retrieve array data for the caller (in our program, the Java front-end). The last prototype corresponds to the function which actually calls the Process Manager.

Notice that all of the return values are long integers. This is because of the translation of Java primitive data types to Macintosh data types, which we will examine shortly.

Now we can look at the implementation of those functions. This is a partial listing of the contents of ProcessWatcher.c. We will view the remainder shortly.

Listing 2: ProcessWatcher.c

ProcessWatcher.c
Retrieve and save information about currently running processes.

/**************************
  DoGetNumRecords
**************************/
long    DoGetNumRecords( void )
{
  return( ( long )gNumRecords );
}

/**************************
  DoGetCurrentSize
**************************/
long    DoGetCurrentSize( long i )
{
  return( gArray[ i ].currentSize );
}
/**************************
  DoGetProcessSize
**************************/
long    DoGetProcessSize( long i )
{
  return( gArray[ i ].processSize );
}

/**************************
  DoGetProcessNameLength
**************************/
long    DoGetProcessNameLength( long i )
{
  return( gArray[ i ].processName[ 0 ] );
}

/**************************
  DoGetProcessNameChar
**************************/
long    DoGetProcessNameChar( long i, long j )
{
  return( gArray[ i ].processName[ j ] );
}

/**************************
  DoGetProcessInfo
**************************/
//  This routine walks through the current process list
//  and retrieves information we need.
void    DoGetProcessInfo( void )
{
  FSSpec              theSpec;
  OSErr              theError;
  ProcessInfoRec      theInfoRec;
  ProcessSerialNumber  thePSN;
  Str32              theName;
  
  //  Reset the array count.
  gNumRecords = 0;

  //  Setup the record for retrieving process info.
  theInfoRec.processInfoLength = sizeof( ProcessInfoRec );
  theInfoRec.processName = theName;
  theInfoRec.processAppSpec = &theSpec;
  
  thePSN.highLongOfPSN = NIL;
  thePSN.lowLongOfPSN = kNoProcess;

  //  Retrieve process info until no more processes are found.
  while ( GetNextProcess( &thePSN ) == noErr )
  {
    theError = GetProcessInformation( &thePSN, &theInfoRec );

    if ( theError != noErr )
      break;

    //  Save the process data into the global array. Start with the process name.
    BlockMove( ( Ptr )theInfoRec.processName, 
      ( Ptr )gArray[ gNumRecords ].processName, 
      STRING_LENGTH );

  //  Partition sizes are 16 bytes off when compared to "About This Macintosh".
  //  Current sizes are 15 bytes off when compared to "About This Macintosh".
  //  Adjust and store the resulting values so our display matches the system display.
    gArray[ gNumRecords ].processSize = 
      ( theInfoRec.processSize / ONE_KBYTE_SIZE ) 
      - DIFFERENCE_FACTOR;
    gArray[ gNumRecords ].currentSize = (
      ( theInfoRec.processSize - theInfoRec.processFreeMem ) 
      / ONE_KBYTE_SIZE ) - DIFFERENCE_FACTOR + 1;

    gNumRecords++;
    
    //  Bounds checking.
    if ( gNumRecords > MAX_NUM_RECORDS )
      break;
  }
}

This is a good start, so now we turn our attention to the Java class that contains the native methods. Remember, these are the Java calls to our C code.

We will abstract this portion of the design slightly to allow some flexibility. This means that the names of the native methods will not match the function names just described, although they have a similar purpose. Why is this? To allow us to make minor modifications to either piece without affecting the other. For instance, we can change the variable names in the C code, and the Java class still performs the same as before.

Let's take a closer look at the Java class containing the native methods.

Native Methods in a Java Class

To use the shared library, Java requires a class definition that both loads the library and calls the native methods within it. It also requires method declarations inserted in the calling class file matching the prototype for the called function. Notice that these declarations contain arguments but no body, ending in a semicolon (similar to a function prototype). The keyword 'native' tells the compiler that the code for these methods will be defined elsewhere.

Listing 3 shows the Java code for our native class (NProcessWatcher). The purpose of the static initializer is to ensure that the shared library gets loaded when this class gets loaded. (For details on the loading process, refer to Inside Macintosh: PowerPC System Software, and its discussion of the Code Fragment Manager.)

Listing 3: NProcessWatcher.java

NProcessWatcher.java
The class that will interface to our shared library.

public class NProcessWatcher
{
  //  Tell the VM to load our shared library.
  static
  {
    System.loadLibrary("ProcessWatcher Library");
  }
  
  //  Here are definitions for several simple native methods. Note that the data types 
  //  we specify here may not be the same in the corresponding header file, due to 
  //  size differences between Java's primitive types and the Macintosh's data types. 
  //  The stubs file should handle thetranslation of the arguments and return types 
  //  for us.
  
  //  This method invokes the Process Manager portion of the shared library.
  private native void nativeGetProcessInfo();
  
  //  The following methods retrieve various pieces of information
  //  about the current processes. 
  private native int nativeGetNumElements();
  
  private native int nativeGetCurrentSize( int i );
  
  private native int nativeGetProcessSize( int i );
  
  private native int nativeGetProcessNameLength( int i );
  
  private native char 
    nativeGetProcessNameChar( int i, int j );
  
  //  Our class constructor. It calls our native method
  //  that updates the Process Manager information.
  public NProcessWatcher()
  {
    this.nativeGetProcessInfo();
  }

  //  Update the Process Manager information on request.
  public void updateNow()
  {
    this.nativeGetProcessInfo();
  }

  //  Accessor methods used by our other Java classes to get process info. By hiding 
  //  the actual calls to the native methods, we can change the implementation 
  //  without affecting the classes calling in. 
  public int getNumElements()
  {
    return( this.nativeGetNumElements() );
  }

  public int getCurrentSize( int i )
  {
    return( this.nativeGetCurrentSize( i ) );
  }

  public int getProcessSize( int i )
  {
    return( this.nativeGetProcessSize( i ) );
  }

  public int getProcessNameLength( int i )
  {
    return( this.nativeGetProcessNameLength( i ) );
  }

  public char getProcessNameChar( int i, int j )
  {
    return( this.nativeGetProcessNameChar( i, j ) );
  }
}

With this class defined, we can now compile it. It does not rely on any other classes, so it will compile by itself using the Java Compiler in the JDK.

We still need a way to tie together this class and our shared library. Specifically, we need two additional files. One is a second header file, containing the prototypes for the Java calls into the C code. The other is a stubs file that can handle the translation of arguments and return values between our Java and C code. The JDK provides a tool that will handle this for us: JavaH.

The JavaH utility generates the header and stub files from the class file containing the native methods. After you compile NProcessWatcher.java, drop the resulting class file (NProcessWatcher.class) on the JavaH icon. This should create NProcessWatcher.h and NProcessWatcher.stubs in the same folder as JavaH.

Move these two files into the folder containing your CodeWarrior project before building the library. You should not modify these files. However, we must use of the information in the header file. If you open NProcessWatcher.h, you will see the native method declarations, rewritten as C function prototypes.

Listing 4: NProcessWatcher.h

NProcessWatcher.h
The JavaH generated header file for our native methods. This listing is
reformatted to fit the magazine page.

#include <native.h>

/* header for class NProcessWatcher */
#ifndef _Included_NProcessWatcher
#define _Included_NProcessWatcher
#ifdef __cplusplus
extern "C" {
#endif
typedef struct ClassNProcessWatcher {
  char pad[1];  /* Padding for ANSI C */
} ClassNProcessWatcher;

HandleTo(NProcessWatcher);

extern void NProcessWatcher_nativeGetProcessInfo
              (struct HNProcessWatcher*);
extern long NProcessWatcher_nativeGetNumElements
              (struct HNProcessWatcher*);
extern long NProcessWatcher_nativeGetCurrentSize
              (struct HNProcessWatcher*, long);
extern long NProcessWatcher_nativeGetProcessSize
              (struct HNProcessWatcher*, long);
extern long NProcessWatcher_nativeGetProcessNameLength
              (struct HNProcessWatcher*, long);
extern /*unicode*/ long
              NProcessWatcher_nativeGetProcessNameChar
              (struct HNProcessWatcher*, long, long);
#ifdef __cplusplus
}
#endif

#endif /* _Included_NProcessWatcher */

Copy the six prototypes over to ProcessWatcher.c, and paste them near the top, after the #includes. Delete the word "extern" at the front of each one. Now we can fill in the bodies for these functions. Here is the revised version of ProcessWatcher.c:

Listing 2 revisited: ProcessWatcher.c

ProcessWatcher.c
Retrieve and save information about currently running processes.

//  Implementation of a native shared library for MacOS.
//  Adapted from the example provided with the JDK v1.0.2.

//  OS Headers
#include <CodeFragments.h>

//  JavaH generated Header
#include "NProcessWatcher.h"

//  Our library header.
#include "ProcessWatcher.h"

//  The first functions listed are the calls into our native library. They match the 
//  prototypes in the header file NProcessWatcher.h, which we included above.

//  The Java data types (int and char) expected as return types by NProcessWatcher.java 
//  map to the long int data type on the Macintosh. We didn't arbitrarily select this; it 
//  was generated by JavaH as part of NProcessWatcher.h

//  We have functions calling functions to get the process data.
//  This allows us to change the underlying implementation if necessary.

void NProcessWatcher_nativeGetProcessInfo
              (struct HNProcessWatcher* self)
{
  DoGetProcessInfo();
}

long NProcessWatcher_nativeGetNumElements
              (struct HNProcessWatcher* self)
{
  return( DoGetNumRecords() );
}

long NProcessWatcher_nativeGetCurrentSize
              (struct HNProcessWatcher* self, long i)
{
  return( DoGetCurrentSize( i ) );
}

long NProcessWatcher_nativeGetProcessSize
              (struct HNProcessWatcher* self, long i)
{
  return( DoGetProcessSize( i ) );
}

long NProcessWatcher_nativeGetProcessNameLength
              (struct HNProcessWatcher*, long i)
{
  return( DoGetProcessNameLength( i ) );
}

long NProcessWatcher_nativeGetProcessNameChar
              (struct HNProcessWatcher*, long i, long j)
{
  return( DoGetProcessNameChar( i, j ) );
}

/**************************
  DoGetNumRecords
**************************/

long    DoGetNumRecords( void )
{
  return( ( long )gNumRecords );
}

/**************************
  DoGetCurrentSize
**************************/

long    DoGetCurrentSize( long i )
{
  return( gArray[ i ].currentSize );
}

/**************************
  DoGetProcessSize
**************************/

long    DoGetProcessSize( long i )
{
  return( gArray[ i ].processSize );
}

/**************************
  DoGetProcessNameLength
**************************/

long    DoGetProcessNameLength( long i )
{
  return( gArray[ i ].processName[ 0 ] );
}

/**************************
  DoGetProcessNameChar
**************************/

long    DoGetProcessNameChar( long i, long j )
{
  return( gArray[ i ].processName[ j ] );
}

/**************************
  DoGetProcessInfo
**************************/

//  This routine walks through the current process list
//  and retrieves information we need.
void    DoGetProcessInfo( void )
{
  FSSpec              theSpec;
  OSErr              theError;
  ProcessInfoRec      theInfoRec;
  ProcessSerialNumber  thePSN;
  Str32              theName;
  
  //  Reset the array count.
  gNumRecords = 0;

  //  Setup the record for retrieving process info.
  theInfoRec.processInfoLength = sizeof( ProcessInfoRec );
  theInfoRec.processName = theName;
  theInfoRec.processAppSpec = &theSpec;
  
  thePSN.highLongOfPSN = NIL;
  thePSN.lowLongOfPSN = kNoProcess;

  //  Retrieve process info until no more processes are found.
  while ( GetNextProcess( &thePSN ) == noErr )
  {
    theError = GetProcessInformation( &thePSN, &theInfoRec );

    if ( theError != noErr )
      break;

    //  Save the process data into the global array. Start with the process name.
    BlockMove( ( Ptr )theInfoRec.processName, 
      ( Ptr )gArray[ gNumRecords ].processName, 
      STRING_LENGTH );

    //  Partition sizes are 16 bytes off when compared to "About..."
    //  Current sizes are 15 bytes off when compared to "About..."
    gArray[ gNumRecords ].processSize = 
      ( theInfoRec.processSize / ONE_KBYTE_SIZE ) 
      - DIFFERENCE_FACTOR;
    gArray[ gNumRecords ].currentSize = ( 
      ( theInfoRec.processSize - theInfoRec.processFreeMem ) 
      / ONE_KBYTE_SIZE ) - DIFFERENCE_FACTOR + 1;

    gNumRecords++;
    
    //  Bounds checking.
    if ( gNumRecords > MAX_NUM_RECORDS )
      break;
  }
}

Each prototype contains the class name, followed by an underscore, then the name of the native method from the class. The parameters include a reference to the calling class, and any arguments. The first function is declared as void, and simply calls another void function in this c file. The other functions accept parameters and return values. We specified Java integers in the original method declarations, and we see here that they were adjusted (by JavaH) to Macintosh long ints in the header file to correspond to the 32-bit data type.

These functions call other functions in this file to get process data. Those values are then returned to the caller (NProcessWatcher).

One more step is required before we attempt to make the shared library project. Make an alias to the file "Java Shared Library", which is located in the path System Folder:Extensions:JavaSoft Folder. Place the alias into the folder containing the shared library project.

The Project Definition

Figure 1 shows the CodeWarrior project definition.

Figure 1. The CodeWarrior project.

Here are several of the project preferences settings necessary to create the shared library:

PPC Project:
File Name:    ProcessWatcher Library
Creator:    Java
Type:      shlb

PPC PEF:
Fragment Name:  ProcessWatcher Library
Library Folder ID:  0

Our shared library is actually a code fragment. The Preferred Executable Format (PEF) dictates the layout of the generated fragment. The Fragment Name will be used by the Code Fragment Manager to identify and load the fragment. We don't use the Library Folder ID setting: it is for specifying the ID of an alias resource, which points to a directory containing other libraries that our fragment uses.

We also do not use the version numbers (also in the PPC PEF window), preferring to leave them at 0 (zero). If you create additional versions of the library, and do not maintain backward compatibility, you can use version numbers to specify which versions of other fragments may call in to (or be called by) this fragment.

There are no initialization or termination entry points defined for this project. As indicated in the CodeWarrior documentation, such functions could be used to setup or teardown the resources or memory needed by the fragment. There is no main entry point for a shared library, and so we do not specify one.

Figure 2 shows the files used in creating the native library. (A copy of the shared library is also shown.)

Figure 2. The files used to build the native library.

These are the contents of the files shown in Figure 2:

  • Java Shared Library: an alias to a file in the JavaSoft folder, required during the build.
  • NProcessWatcher.h: header for ProcessWatcher. Generated by JavaH.
  • NProcessWatcher.stubs: stubs for ProcessWatcher. Generated by JavaH.
  • ProcessWatcher.c: the calls to the MacOS ProcessManager.
  • ProcessWatcher.h: constant definitions and function prototypes for ProcessWatcher.c.
  • ProcessWatcher.n: project definition file.
  • libstubs_example.c: export information for use by CodeWarrior.

For this last file, I kept the same name as the original included with the JDK, but modified the contents to include NProcessWatcher.stubs.

You can now make this project by pressing Command-M, which will compile and link the code. The compiler should place the shared library file "ProcessWatcher Library" in the project directory.

Java Class Interactions

We can now turn our attention to the Java portion of our program. We have already looked at NProcessWatcher, which contains the native method calls. Figure 3 shows the names of all of the Java class and source code files.

Figure 3. The Java source and class files for the front-end.

Here is the purpose of each Java source code file:

  • Globals: constants used throughout the other classes.
  • NProcessWatcher: calls the native code shared library.
  • PrefsDialog: the preferences dialog.
  • ProcessInfo: data storage for information about each process.
  • ProcessWatcher: the front-end and main window.
  • Updater: the thread which periodically calls NProcessWatcher.

Figure 4 illustrates the interaction between the Java classes and the library.

Figure 4. Class file and library interaction.

These interactions are defined as follows:

  1. The Java front-end(ProcessWatcher) creates a Java thread (Updater), and starts it running.
  2. Updater creates an instance of the class NProcessWatcher, which interfaces with the shared library. NProcessWatcher loads the PPC shared library (ProcessWatcher Library).
  3. NProcessWatcher calls a native function within ProcessWatcher Library, instructing it to retrieve and save the current Process Manager information.
  4. Updater tells ProcessWatcher to request and display the process information.
  5. Updater goes to sleep. On wake up, return to step 3.

In addition, ProcessWatcher calls PrefsDialog when the user clicks the Prefs button. If the user updates the settings, the changes are signaled back to ProcessWatcher.

The Java Front-End

The Java front-end is a window that looks vaguely similar to the "About This Macintosh" window under the Apple Menu (refer to Figure 5).

Figure 5. The finished product.

When launched, the front-end retrieves and displays some information about the operating system and architecture. Then it creates a thread that calls the native code in the shared library. The thread instructs the front-end to update its window, then goes to sleep for a user-specified number of seconds. When it receives the update message from the thread, the front-end communicates with the shared library using the native methods described previously. It retrieves a count of the number of processes, then the partition size, RAM in use, and name for each process. The front-end then draws RAM usage bars in its window.

The front-end has three buttons near the bottom: Quit, Update, and Prefs. Quit leaves the application. Update performs an immediate update of the data displayed in the window. This is the same action taken when the thread informs the window to update, but using the button it can be done on demand. Clicking the Prefs button displays the preferences dialog.

For simplicity, the user interface items are placed using absolute values (screen coordinates). Note that this may affect the look of the front-end if you use it on a non-Macintosh platform. (Of course, you would also have to rewrite the shared library for the new platform.)

The preferences dialog is a moveable modal dialog, as shown in Figure 6. It contains a text field, a scrollbar, and Cancel and OK buttons. The text field shows the sleep setting for the thread (in seconds). It is set to non-editable, and its contents are highlighted. It gets updated with new values as the user moves the scrollbar. The scrollbar is horizontal. Larger values are to the right. Clicking Cancel will dismiss the dialog without saving any changes the user made to the sleep setting. Clicking OK will save the changes, then dismiss the dialog. Settings are kept internally; they are not written out to a preferences file.

Figure 6. The Preferences dialog.

The scrollbar event-handling is related to the text field in this way: when the user clicks in the scrollbar or moves the thumb, the appropriate event is caught, and the number in the text field changes appropriately. Currently, page up and page down events are not handled. Scrollbar event handling is accomplished by overriding the handleEvent() method in PrefsDialog.

The updater thread leads a simple life. Once created, it goes through a continuous cycle. It first creates an instance of the native class, which is responsible for calling the native methods (which invoke the C functions). Next, the thread tells its parent (the front-end) to update its display. Finally, the thread goes to sleep for the user-specified sleep interval. When it wakes up, if the native object has been destroyed for some reason, it gets recreated. Otherwise, the thread instructs both the native object and the parent object to perform their respective update operations.

Listing 6 contains the code for requesting process information from the shared library, and the paint() method used to display it. Here is the method that requests the process information. Notice that it retrieves the process names one character at a time into a character array, then converts that array to a String.

Listing 6: ProcessWatcher.java (partial listing)

ProcessWatcher.java
The front-end for our Java application.

  public void readProcessInfo()
  {
    //  Retrieve the reference to our native class, maintained by the Updater.
    NProcessWatcher  tempNProcessWatcher =
      theUpdaterThread.doGetNativeClass();

    //  If the native class has not been instantiated yet, leave.
    if ( tempNProcessWatcher == null )
      return;

    //  Clear out the Vector.
    theProcessList.removeAllElements();

    //  Counters for traversing the array of processes, 
    //  and the individual process names.
    int  i = 0, j = 0;
    
    //  So we know when we've retrieved all the process elements...
    int  max = tempNProcessWatcher.getNumElements();

    //  Walk through the process elements one at a time.
    for ( i = 0; i < max; i++ )
    {
      //  Retrieve process size info from the native class.
      int theCurRAM = 
            tempNProcessWatcher.getCurrentSize( i );
      int thePartition = 
            tempNProcessWatcher.getProcessSize( i );
      
      //  How long is the process name?
      int theLength = 
            tempNProcessWatcher.getProcessNameLength( i );

      //  We'll hardcode a max name size. It must be at least as 
      //  large as the name size in the C code (32).
      char[] theCharArray = new char[ 32 ];

      //  Get the process name, one character at a time. Note the dual 
      //  counters used to get the char:
      //    i is the current process array element, and
      //    j + 1 is a character in the name (Str32) for that process.
      //  Our character array starts its element numbering at 0, but the Str32 data 
      //  type (used in the C code) uses location 0 for the length of the string, so 
      //  we have to adjust the counter j to start one element beyond it.
      for ( j = 0; j < theLength; j++ )
        theCharArray[ j ] = 
        tempNProcessWatcher.getProcessNameChar( i, j + 1 );

      //  Once the char array is filled in, create a Java String from it.
      String theNameString = new String( theCharArray );

      //  Create a new instance of the ProcessInfo class, fill in
      //  the values, then place the reference to the object into the Vector.
      ProcessInfo tempProcessInfo = new ProcessInfo();
      tempProcessInfo.setCurRAM( theCurRAM );
      tempProcessInfo.setPartition( thePartition );
      tempProcessInfo.setName( theNameString );
      theProcessList.addElement( tempProcessInfo );

      //  Force changes to redraw.
      repaint();
    }

Listings 6 through 8 contain the Java code for the front-end, preferences dialog, and updater thread, respectively. Listing 9 contains definitions for various constants used throughout the Java classes. These listings are fairly well structured, and should be easy to read.

Conclusion

Calling C code from Java requires some preparation. You must properly construct a PowerPC shared library and define methods within your Java classes for calling this library. We explored the steps necessary to get data from the Process Manager to a shared library and then to a Java front-end for display. In situations where you need Macintosh Toolbox functionality that Java does not inherently provide, a shared library can be an effective solution. This approach is supported by Sun, so it makes sense to use it if necessary.

References

  1. Inside CodeWarrior 8, Metrowerks Inc., 1996.
  2. Inside Macintosh: PowerPC System Software, Apple Computer, Inc., Addison-Wesley Publishing Company, 1994.
  3. Teach Yourself Java in 21 Days, Laura Lemay and Charles L. Perkins, Sams.net Publishing, 1996.

URLs

Source files: http://www1.omi.tulane.edu/adowns/MacTech/source/.


Andrew Downs, andrew.downs@tulane.edu, is a programmer for the Office of Medical Informatics at the Tulane University School of Medicine in New Orleans, LA. He also teaches C and Java programming at Tulane University College. Andrew wrote the Macintosh shareware program Net Manager, and the Java application UDPing.

 
AAPL
$118.85
Apple Inc.
-0.15
MSFT
$48.10
Microsoft Corpora
+0.35
GOOG
$541.36
Google Inc.
+0.99

MacTech Search:
Community Search:

Software Updates via MacUpdate

Skype 7.2.0.412 - Voice-over-internet ph...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
HoudahSpot 3.9.6 - Advanced file search...
HoudahSpot is a powerful file search tool built upon MacOS X Spotlight. Spotlight unleashed Create detailed queries to locate the exact file you need Narrow down searches. Zero in on files Save... Read more
RapidWeaver 6.0.3 - Create template-base...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
iPhoto Library Manager 4.1.10 - Manage m...
iPhoto Library Manager lets you organize your photos into multiple iPhoto libraries. Separate your high school and college photos from your latest summer vacation pictures. Or keep some photo... Read more
iExplorer 3.5.1.9 - View and transfer al...
iExplorer is an iPhone browser for Mac lets you view the files on your iOS device. By using a drag and drop interface, you can quickly copy files and folders between your Mac and your iPhone or... Read more
MacUpdate Desktop 6.0.3 - Discover and i...
MacUpdate Desktop 6 brings seamless 1-click installs and version updates to your Mac. With a free MacUpdate account and MacUpdate Desktop 6, Mac users can now install almost any Mac app on macupdate.... Read more
SteerMouse 4.2.2 - Powerful third-party...
SteerMouse is an advanced driver for USB and Bluetooth mice. It also supports Apple Mighty Mouse very well. SteerMouse can assign various functions to buttons that Apple's software does not allow,... Read more
iMazing 1.1 - Complete iOS device manage...
iMazing (was DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and from... Read more
PopChar X 7.0 - Floating window shows av...
PopChar X helps you get the most out of your font collection. With its crystal-clear interface, PopChar X provides a frustration-free way to access any font's special characters. Expanded... Read more
OneNote 15.4 - Free digital notebook fro...
OneNote is your very own digital notebook. With OneNote, you can capture that flash of genius, that moment of inspiration, or that list of errands that's too important to forget. Whether you're at... Read more

Latest Forum Discussions

See All

Monster Strike Review
Monster Strike Review By Campbell Bird on November 28th, 2014 Our Rating: :: BILLIARD STRATEGYUniversal App - Designed for iPhone and iPad Collect monsters and battle by flinging them across the battlefield in this strangely... | Read more »
Proun+ Review
Proun+ Review By Jennifer Allen on November 28th, 2014 Our Rating: :: TWITCHY RACINGUniversal App - Designed for iPhone and iPad Twitchy racing aplenty in Proun+, an enjoyably tricky title.   | Read more »
Lucha Amigos (Games)
Lucha Amigos 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Forget Ninja Turtles, and meet Wrestlers Turtles! Crazier, Spicier and…Bouncier! Sling carapaces of 7 Luchadores to knock all... | Read more »
Record of Agarest War Zero (Games)
Record of Agarest War Zero 1.0 Device: iOS Universal Category: Games Price: $7.99, Version: 1.0 (iTunes) Description: HyperDevbox Holiday Turkey Black Friday Special Pricing! To celebrate the opening of the holiday season HyperDevbox... | Read more »
Raby (Games)
Raby 1.0.3 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.3 (iTunes) Description: ***WARNING - Raby runs on: iPhone 5, iPhone 5C, iPhone 5S, iPhone 6, iPhone 6 Plus, iPad Mini Retina, iPad Mini 3, iPad 4, iPad Air,... | Read more »
Oddworld: Stranger's Wrath (Games)
Oddworld: Stranger's Wrath 1.0 Device: iOS Universal Category: Games Price: $5.99, Version: 1.0 (iTunes) Description: ** PLEASE NOTE: Oddworld Stranger's Wrath requires at least an iPhone 4S, iPad 2, iPad Mini or iPod Touch 5th gen... | Read more »
Bounce On Back (Games)
Bounce On Back 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: | Read more »
Dwelp (Games)
Dwelp 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: === 50% off for a limited time, to celebrate release === Dwelp is an elegant little puzzler with a brand new game mechanic. To complete a... | Read more »
Make Way for Fat Chicken, from the Maker...
Make Way for Fat Chicken, from the Makers of Scrap Squad Posted by Jessica Fisher on November 26th, 2014 [ permalink ] Relevant Games has announced they will be releasing their reverse tower defense game, | Read more »
Tripnary Review
Tripnary Review By Jennifer Allen on November 26th, 2014 Our Rating: :: TRAVEL BUCKET LISTiPhone App - Designed for the iPhone, compatible with the iPad Want to create a travel bucket list? Tripnary is a fun way to do exactly that... | Read more »

Price Scanner via MacPrices.net

Black Friday: 27-inch 5K iMac for $2299, save...
 B&H Photo continues to offer Black Friday sale prices on the 27″ 3.5GHz 5K iMac, in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP... Read more
Karalux Announces 24K Gold-Plated iPhone 6
Karalux, a Vietnam-based jewellery firm, has launched a unique 24 karat gold-plated iPhone 6 version with gold-cast monolithic dragon on its back panel. The real 24 karat gold plated enclosure doesn’... Read more
Black Friday: 13-inch 2.6GHz Retina MacBook P...
 B&H Photo has lowered their price for the 13″ 2.6GHz/128GB Retina MacBook Pro to $1159 for Black Friday. That’s $140 off MSRP, and it’s the lowest price for this model (except for Apple’s $1099... Read more
View all the Black Friday sales on our Mac Pr...
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers. View Black Friday sale prices at a... Read more
Black Friday: 11-inch MacBook Air for $779, s...
 Best Buy has lowered their price for the 2014 11″ 1.4GHz/128GB MacBook Air to $779.99 for Black Friday. That’s $120 off MSRP. Choose free shipping or free local store pickup (if available). Sale... Read more
Apple Store Black Friday sale for 2014: $100...
BLACK FRIDAY The Apple Store has posted their Black Friday deals for 2014. Receive a $100 PRODUCT(RED) branded iTunes gift card with the purchase of select Macs, $50 with iPads, and $25 with iPods,... Read more
Black Friday: 15% off iTunes Gift Cards
Staples is offering 15% off $50 and $100 iTunes Gift Cards on their online store as part of their Black Friday sale. Click here for more information. Shipping is free. Best Buy is offering $100... Read more
BEVL Releases Dock Tailored for iPhone 6 and...
Seattle based BEVL has released their first product: an iPhone dock that is divergent in build quality, rock-solid function and visual simplicity to complement the iPhone. BEVL is now accepting... Read more
Black Friday: $150 off 13-inch Retina MacBook...
 Best Buy has 13-inch 2.6GHz Retina MacBook Pros on sale for $150 off MSRP on their online store as part of their Black Friday sale. Choose free shipping or free local store pickup (if available).... Read more
Black Friday: $300 off 15-inch Retina MacBook...
 B&H Photo has the new 2014 15″ Retina MacBook Pros on sale for $300 off MSRP as part of their Black Friday sale. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.