Additional file for previous patch

Glenn Chambers GChambers@provsol.com
Wed Dec 29 11:10:00 GMT 1999


This goes into 'jni-kaffe.txt'.

-----Original Message-----
From: Glenn Chambers 
Sent: Wednesday, December 22, 1999 1:17 PM
To: 'Anthony Green'
Subject: RE: what happend to expanded gcj faq?


This is a trivial example of a JNI native method intended
to provide a comparision with the GCJ CNI example.

This was built using the Kaffe JVM on a RedHat 6.0 system;
substitute 'javah' for 'kaffeh' for Sun's JDK.

==> Makefile <==
libsampNat.so: sampNat.o
	gcc -shared -o libsampNat.so sampNat.o

sampNat.o: sampNat.c sample.h
	gcc -I/usr/include/kaffe -c sampNat.c

sample.h:  sample.class
	kaffeh -jni sample

sample.class: sample.java
	javac sample.java

clean:
	rm -f sample.h sample.class sampNat.o libsampNat.so

==> sampNat.c <==
#include <jni.h>
#include "sample.h"
#include <stdio.h>

JNIEXPORT void JNICALL Java_sample_myNative(JNIEnv* env, jobject this, 
                                            jstring s)
{
  jclass cls;
  jfieldID fid;
  jobject obj;
  jmethodID mid;

  printf("From C\n");

  cls = (*env)->FindClass(env, "java/lang/System");
  if (cls == 0) {
    printf("java/lang/System lookup failed\n");
    return;
  }
  fid = (*env)->GetStaticFieldID(env, cls, "out", "Ljava/io/PrintStream;");
  if (fid == 0) {
    printf("java/lang/System::out lookup failed\n");
    return;
  }
  obj = (*env)->GetStaticObjectField(env, cls, fid);
  if (obj == 0) {
    printf("GetStaticObjectField call failed\n");
    return;
  }
  cls = (*env)->GetObjectClass(env, obj);
  if (cls == 0) {
    printf("GetObjectClass(out) failed\n");
    return;
  }
  mid = (*env)->GetMethodID(env, cls, "println", "(Ljava/lang/String;)V");
  if (mid == 0) {
    printf("println method lookup failed\n");
    return;
  }
  (*env)->CallVoidMethod(env, obj, mid, s);
}

==> sample.java <==
public class sample {
  public native void myNative(String s);

  public void myJava(String s) {
    s = s + ", Java";
    System.out.println(s);
  }

  public static void main(String args[]) {
    sample x = new sample();
    x.myJava("Hello");
    x.myNative("Hello, Java (from C)");
    x.myJava("Goodbye");
  }
  
  static {
    System.loadLibrary("sampNat");
  }
}


More information about the Java-patches mailing list