Applets calling native methods

New Articles

J2ME and the 6600.

Megaupload - File upload progress bar.

The Swing slow paint problem

In the previous step we figured out how to accept a return value from a native method. (Earlier we looked at how a java class can call native methods). Now we will look at how we can do the same with an applet. You should already be familiar with how to create a signed applet.

Our applet will call a C function and embed it's return value into a JLabel. The JLabel will be displayed in the Applet's content pane. Notice how the System.load() call has to be placed inside a privileged block.

    public NativeHelloApplet() {
	AccessController.doPrivileged(new PrivilegedAction() {
	    public Object run() {
		try {
		    System.load(System.getProperty("user.home") +"/");
		}catch(Exception e) {
		return null;

You need to produce the header file and compile the library just as we did in the earlier steps. Follow that up by creating a jar file for the applet. Then you have to sign the jar file. It is only then that we can finally load it up in our browser. Don't forget to copy to your home directory. Since ours is a signed applet it will be able to read the library from the hard disk.

If you examine the header and C source files you will see that they are very differet when moving from the stand-alone version to the applet. According to the JNI naming convention the name of the C function is dependent not just on the java class name but on it's package name as well. That obviously means you should use Java Native Interface only as an Interface. The bulk of your C code should be placed in other functions which you can then call from the function defined in the javah generated header.

We are essentialy done but there is room for improvement. We can refine our code to load different libraries for different operating systems. We can also add a test to ensure that we load the library only once. If we attempt to load it twice it will fail. All that is left as an excercise. You can start of on it by downloading the code

Goto Page : 1  ,  2 ,  3