Using VC++ components from Java program

This article describes how to access native windows dll from Java programs to take advantages of facilities provided by windows which are not possible to use directlly from Java. It introduces JNI ( Java native interface )

Introduction

JNI is my favourite programming framework in Java; it gives you freedom to use natively created code. For example, if you want to use any Windows API (i.e. dll) from your Java code, you can use JNI.

The most popular advantage of Java is platform independence. However, sometimes this feature makes it very difficult to integrate Java programs with native platforms.

For example, in our project we are using MSM Q (Microsoft Messaging Que) for a queuing mechanism to maintain messages (to avoid loss of messages) before writing them to the database. Microsoft is providing MSM Q API which is a Windows' API. But our program produces messages is in Java, and Java can't directly access such VC++ API (dll). So we have decided to make an intermediate DLL which will be work as bridge between Java and VC++ (we have used the technology Java Native Interface, or JNI).

Before proceeding further, you should know / be familiar with some terms.

Native Methods: Native method is a method whose declaration would be in a .java file and the definition would be in your native code. (for Window's it is in VC++).

Here, the third argument is your argument from Java program. You can convert it to the native form as:

constchar *strS1 = env->GetStringUTFChars( s1, 0);

Here you can use strS1 in the program as a C++ string. In the demo program I have used it to display it in Messagebox. There are many methods of JNIEnv by which we can convert various types of data from Java to C++.

Releasing the string after use is compulsory, and is not automatic. JNI activities are presumed to be external to JVM, so it will not throw any kind of exception which could be caught in Java code. If you forget to release the string before leaving the function, this could result in the crashing of your JVM.