Showing posts with label JNI. Show all posts
Showing posts with label JNI. Show all posts

Friday, September 19, 2008

JNI Example

JNI stands for Java Native Interface, which allows you to use, inside your Java application, code written in other programming languages. I will walk you through an example (developed under Windows) of using JNI.

Here are the main steps we need to follow:
- Create a java application that declares the native method.
- Compile the program.
- Generate the header file using javah.
- Implement the native code inside a C application.
- Compile the C code and generate the native library (dll).
- Run the java program.

Let us go through each of these steps:

1. Create a java application that declares the native method.

/**
* Shows a simple example of using JNI
*/
public class JNIExample {
//Declare native method
private native void displayMessage();

public static void main(String[] args) {
//Load native library
System.loadLibrary("JNIExample");
//Call the native method
new JNIExample().displayMessage();
}
}


2. Compile the program.
javac JNIExample.java

3. Generate the header file using javah.
javah -jni JNIExample

4. Implement the native code inside a C application.

#include
#include
#include "JNIExample.h"

JNIEXPORT void JNICALL Java_JNIExample_displayMessage
(JNIEnv *lEnv, jobject lObj) {
printf("This is a JNI Example!\n");
return;
}

The method signature matches exactly the one from the JNIExample.h header file.

5. Compile the C code and generate the native library (dll).
Open a Visual Studio (or similar) command prompt. In my case, it was located under "start->Programs->Visual C++ 2005 Express Edition->Visual Studio Tools->Visual Studio 2005 Command Prompt".
Run the command from the directory where you have the JNIExample.c file:
"cl -I"c:\Program Files\Java\jdk1.5.0_08\include" -I"c:\Program Files\Java\jdk1.5.0_08\include\win32" -MD -LD JNIExample.c -FeJNIExample.dll". Your path to the include directory might be different, so make sure you adjust that according to your settings. The -LD option makes sure that the compiler generates a DLL file. The -MD option makes sure that the DLL generated is linked with the win32 multithreaded C library.

6. Run the Java program.
java JNIExample

Some problems I ran into it while testing the code:
- I was missing the msvcr80.dll file, so I downloaded from here and copied it to c:\windows\system32 directory.
- Even though a manifest file was created, I hade to embedd it inside the dll. I have used the following link to solve the problem: http://msdn.microsoft.com/en-us/library/ms235591(VS.80).aspx. Here is the command: "mt.exe -manifest JNIExample.dll.manifest -outputresource:JNIExample.dll;2"