Using Java as a Graphical User Interface for C Library Routines

Introduction

Java is a very nice language to write high level code. It is well-documented, portable across platforms, and supported with a huge array of support classes. By using Java for a program's Graphical User Interface to call functions in libftdi and libusb, we get the convenience of Java with the speed and proven operation of those C libraries.

Sun Microsystems, the creator of Java, has described how to interface Java code to C code in an online book The Java Native Interface Programmer's Guide and Specification. Chapter 2 of that book is the basis for the HelloWorld.java example that follows. Minor modifications of their compilation procedure, however, were needed for Linux on my system:

Demonstration of C code linkage from Java - HelloWorld.java

  1. Create a Java program called "HelloWorld.java" that contains the following lines:
    class HelloWorld {
    	private native void print();
    	public static void main(String[] args) {
    		new HelloWorld().print();
    	}
    	static {
    		System.loadLibrary("HelloWorld");
    	}
    }
    
  2. Compile HelloWorld.java:
    javac HelloWorld.java
    		
  3. Create a C header using Sun's javah tool:
    javah -jni HelloWorld
    		
  4. Create a sample C shared library source code called "HelloWorld.c":
    #include <jni.h>
    #include <stdio.h>
    #include "HelloWorld.h"
    
    JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj)
    {
    	printf("Hello World from C to Java!\n");
    	return;
    }
    int main(int argc, char** argv){return 0;};
    		
  5. Compile the shared library code:
    cc -shared -fpic -I/usr/java/jdk1.5.0_09/include -I/usr/java/jdk1.5.0_09/include/linux HelloWorld.c -o libHelloWorld.so
    		
  6. Run the code:
    java -Djava.library.path=. HelloWorld
    		
  7. The output should be:
    Hello World from C to Java!
    		

Java version of ftdi_eeprom_main.c

Under Construction

Java version of libftdi_example_bitbang2232.c

Under Construction


Last updated: January 9, 2007

Valid CSS! Valid XHTML 1.0 Strict

Contact Craig Van Degrift if you have problems or questions with this web site.