Developing a Java Class With A Native MethodRecall 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) 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 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).
|