Ask the Expert

Using Java to call a Linux C program from Windows

I have written a C program on the Linux platform. I want a Java interface so that I can access it from my Windows workstation. I know some Java Swing GUIs but don't know how I can call or invoke a C program. Any advice?

    Requires Free Membership to View

To access a C program from Java you need to use the Java Native Interface (JNI) subsystem. The JNI subsystem handles the interactions between Java classes and non-Java libraries.

To use a native library from the JNI subsystem, you must:
A) Prototype the native routines, rebuild the library and place it in the JDK's runtime path
B) Implement Java-to-C and C-to-Java data conversions
C) Load the library from Java using the System.loadLibrary method
D) Declare the native routines to Java

The following example demonstrates JNI prototypes for C routines:
JNIEXPORT void JNICALL Java_MyJavaClass_myNativeRoutine
  (JNIEnv *, jclass, jstring);

  (JNIEnv *, jclass);
The following example demonstrates a conversion from a Java String to a C string:
JNIEXPORT jboolean JNICALL Java_MyJavaClass_myNativeRoutine
  ( JNIEnv *env, jobject obj, jstring jParam)
   /* convert the Java String param */
   const char *cParam = (*env)->GetStringUTFChars(env,
jParam, 0);

   /* use the string */

   /* free the memory used by the C string */
   (*env)->ReleaseStringUTFChars(env, jParam,
cParam);                           }

A complete list of data-type conversions and their usage can be found at:

The following example demonstrates the loadLibrary method and examples of native routine declarations:
class MyJavaClass
         // load the native
      catch( UnsatisfiedLinkError e)
         System.out.println("Error loading native library");

   // declare the native routines
   public static native void myNativeRoutine(String aParam);
   public static native boolean myNextNativeRoutine();
Once the library is loaded, you can make calls to-and-from Java and the native library.

This was first published in February 2004

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: