Problem solve Get help with specific problems with your technologies, process and projects.

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?
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: http://java.sun.com/j2se/1.3/docs/guide/jni/index.html

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 last published in February 2004

Dig Deeper on Microservices pattern, platforms and frameworks



Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

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

Please create a username to comment.