Wednesday, March 29, 2006

Java

I know, you're probably wondering why an article on Java appears on a blog on Win32. Well, it's because Java can call native Win32 code using the JNI interface and I'm posting about my little experiment.

I first created the Java source code like so:

public class jennie {
private native void showMessage(String msg);
static {
System.loadLibrary("genie");
System.out.println("Library loaded");
}
public static void main(String[] args) {
jennie j = new jennie();
j.showMessage("Hola! These are 2 feet.");
}
}


I then compiled the Java source code and used a utility called javah (provided with Sun JDK 1.5) and it generated the following code:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class jennie */

#ifndef _Included_jennie
#define _Included_jennie
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: jennie
* Method: showMessage
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_jennie_showMessage
(JNIEnv *, jobject, jstring);

#ifdef __cplusplus
}
#endif
#endif


Now, I looked up the function prototype and created a method with the exact same name, and included a couple of header files (the jni.h header provided with JDK 1.5 and the javah generated header file, along with others that I call from my function). The resulting source code is like so:

#include
#include
#include

JNIEXPORT void JNICALL Java_jennie_showMessage(JNIEnv* env, jobject, jstring jMsg) {
const char* msg=env->GetStringUTFChars(jMsg, 0);
printf("%s\n", msg);
env->ReleaseStringUTFChars(jMsg, msg);
}

Now, although it's pretty cool that you can call Win32 code from Java, it does look pretty ugly - just take a look at the function prototype and the string conversion!
When it comes to communicating between Win32 and another development platforms, .NET should be your first choice since it's much cleaner (which is because they're both from Microsoft so they want you to stick to their products). There are a few restrictions on communicating between Unmanaged code (Win32) and Managed code so you'd probably want to get more details on it before you go exploring.

0 Comments:

Post a Comment

<< Home