Saturday, January 14, 2012

Java: access DLL file from Java

We can access DLL file from Java using JNI.
JNI is an acronym of Java Native Interface. Using JNI, we can call functions which are written in other languages from Java. 
In the JNI,native functions are implemented in a separate .c or .cpp file. When the JVM invokes the function, it passes a JNIEnv pointer, a jobject pointer, and any Java arguments declared by the Java method. A JNI function may look like this:
JNIEXPORT void JNICALL Java_ClassName_MethodName (JNIEnv *env, jobjectobj)
{
    //Method native implemenation
}


Steps to Achieve:
1. Create a Java Class, with the native method.
2. Compile Java Class
3. Then create a header file using Javah
4. Create a C file using the header created
5. Create a DLL file using 
6. Run the compiled class
In Detail:
1. Java Class:
HelloWorld.java
class HelloWorld
{
        private native void print();
        public static void main(String[] args)
        {
                new HelloWorld().print();
        }
        static{
                System.loadLibrary("CJavaInterface");
        }
}

2. Compile
javac HelloWorld.java

3. Create Header File using Javah
Javah -jni HelloWorld

The above command, create HelloWorld.h file, in the same location where class file is created.

HelloWorld.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class HelloWorld */

#ifndef _Included_HelloWorld
#define _Included_HelloWorld
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     HelloWorld
 * Method:    print
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_HelloWorld_print
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

4. Create a C Class Using Header file

HelloWorld.c

#include "jni.h"
 #include <stdio.h>
 #include "HelloWorld.h"

 JNIEXPORT void JNICALL
 Java_HelloWorld_print(JNIEnv *env, jobject obj)
 {
     printf("Hello World!\n");
     return;
 }

5. Create a DLL file using the below command.

Under Windows, assuming Java is installed in JAVA_HOME = C:\Program Files\Java\jdk1.6.0_15\ (modify accordingly if not), compile and build the DLL in one step:
cl /IJAVA_HOME\include /IJAVA_HOME\include\win32 /Gz /LD HelloWorld.c /FeCJavaInterface.dll

Where

/I<dir> add to include search path
/Gz __stdcall calling convention
/LD flag means "build a DLL."
/Fe flag names the output file as CJavaInterface.dll
6. Run and check the java code
Java HelloWorld
Output:
Hello World!

No comments :

Post a Comment