#include #include #include "HelloWorld.h" JNIEXPORT void JNICALL Java_HelloWorld_print(JNIEnv *env, jobject obj) { jstring Unicode_str; const jbyte *UTF_str; jclass class; jmethodID method_id; jobject this_thread; fprintf(stderr,"Starting Java_HelloWorld_print\n"); /* In C++ the following call would have been written: class = env->FindClass("java/lang/Thread"); */ class = (*env)->FindClass(env, "java/lang/Thread"); if (NULL == class) { fprintf(stderr,"Could not find class java.lang.Thread\n"); return; } method_id = (*env)->GetStaticMethodID(env, class, "currentThread", "()Ljava/lang/Thread;"); if (NULL == method_id) { fprintf(stderr, "Could not find static method currentThread of java.lang.Thread\n"); return; } this_thread = (*env)->CallStaticObjectMethod(env, class, method_id); if (NULL == this_thread) { fprintf(stderr,"Could not get the currentThread\n"); return; } class = (*env)->GetObjectClass(env, this_thread); if (NULL == class) { fprintf(stderr,"Could not find class java.lang.Thread\n"); return; } method_id = (*env)->GetMethodID(env, class, "toString", "()Ljava/lang/String;"); if (NULL == method_id) { fprintf(stderr,"Could not find method toString of java.lang.Thread\n"); return; } Unicode_str = (*env)->CallObjectMethod(env, this_thread, method_id); if (NULL == Unicode_str) { fprintf(stderr,"Did not get the name of the current thread\n"); return; } UTF_str = (*env)->GetStringUTFChars(env, Unicode_str, NULL); if (NULL == UTF_str) { return; /* OutOfMemoryError already thrown */ } /* * Here I *KNOW* that the UTF string returned contains only 7-bit ASCII * characters, that's why I'm passing it to printf. * * When this is *not* the case, see section 8.2 of the JNI Guide... */ printf("Thread \"%s\" says using JNI: Hello World!\n", UTF_str); /* Collecting our garbage to avoid a memory leak */ (*env)->ReleaseStringUTFChars(env, Unicode_str, UTF_str); return; }