Applets calling native methods

More Articles

Custom Look and Feels The Easy Way

Mining The Web Log File.

Java - Javascript interaction

In the previous step we looked at the basic steps that we need follow for a java class to call native methods. Our goal is to call native methods from java applets. Just cut and pasting the code from the previous page into an applet will not work (because many browsers will not display the result of the printf() call in the java console).

So we adapt a different approach; call the native method and display it's return value in the content pane of our applet. But we haven't yet looked at how an applet can call C code, so we make a slight detour and modify the NativeHelloWorld program as follows:

    package com.raditha.articles.jni;

    public class NativeHelloWorld2
	public native String displayHelloWorld();

    	public static void main(String[] args) {
            System.load(System.getProperty("user.home") +"/");
            NativeHelloWorld2 theNative = new NativeHelloWorld2();
            System.out.println("Native Method Said: " + theNative.displayHelloWorld());

When you generate the header as before using javah you will find that the signature of the native method has now changed. It returns a jstring. The jstring type maps to the String type of java. This simple mapping is designed to lull you into a false sense of security.

jstring is not another name for a char array. If our code returns a char array it will fail. You can to convert from native types to java types using the JNIEnv Object. An instance is always passed by the JVM to the native method. The new C code that uses it looks like this:

    Java_com_raditha_articles_jni_NativeHelloWorld2_displayHelloWorld(JNIEnv *env, jobject obj)
	return (*env)->NewStringUTF(env,"Hello world!\n");

In the next step we will see put everything together to create an applet.

Goto Page : 1  ,  2 ,  3