InOnIt.com
Cygwin/Java
FAQ
Calling C from Java
Organizing for JNI
Writing the HelloWorld class
Creating a .h file
Writing the C function
Loading the DLL into the JVM
Running the program
Starting a JVM from C
MLS Playoff Odds
World Football Rankings & World Cup Odds
NCAA Basketball Ratings
Hearts
Personal Home Pages
David's Company

Developing a Java Class With A Native Method

Recall that our approach is that we want to develop Java classes and implement some of the methods in another language (we will be using C).

With that said, let's take a look at our (pure Java) HelloWorld class:


package example.jni;

public class HelloWorld {
	private static void writeHelloWorldToStdout() {
		System.out.println("Hello World");
	}
	
	public static void main(String[] args) {
		writeHelloWorldToStdout();
	}
}

Of course, after performance testing, we've found that writing "Hello World" to the standard output stream has been too much of a performance drain on our application. We'd like to implement the Hello World message in C. To do this, we change our Java code to:


package example.jni;

public class HelloWorld {
	private static native void writeHelloWorldToStdout();
	
	public static void main(String[] args) {
		writeHelloWorldToStdout();
	}
}

Go ahead and compile the given class.

Since our native method will be written in C, it makes no sense for it to contain code (hence, it is a declaration only; vaguely like an abstract method). The Java compiler simply accepts that if a method is declared native, the implementation of the method will be loaded into the VM at runtime.

Just for kicks, let's run the program and see what happens at this point. (We expect it not to work because, among several problems, we haven't bothered writing the native method yet.)

$ java example.jni.HelloWorld
Exception in thread "main" java.lang.UnsatisfiedLinkError: writeHelloWorldToStdout
        at example.jni.HelloWorld.writeHelloWorldToStdout(Native Method)
        at example.jni.HelloWorld.main(HelloWorld.java:8)
Essentially, what the VM is telling us is "you declared this method writeHelloWorldToStdout(), but I can't find it at runtime." As you develop JNI programs, keep your eye out for java.lang.UnsatisfiedLinkError: it's pretty common and means that your VM can't find one of your native methods (for whatever reason).