Java Calling Native Functions in .DLL on Windows

Posted on In Programming

How to call a function in .dll from Java on Windows is introduced in this post with an example.

Platforms used:
OS: Microsoft Windows XP [5.1.2600]

C to .dll compiler: MS Visual Studio 2008

JDK:

java -version
java version "1.6.0_05"
Java(TM) SE Runtime Environment (build 1.6.0_05-b13)
Java HotSpot(TM) Client VM (build 10.0-b19, mixed mode, sharing)

1. Write the Java code

As follows.

public class JNITest {
public static void main (String args[]) {
  if (args.length > 0) {
    int x = new Integer(args[0]).intValue();
    int a = new MyNative().cubecal(x);
    System.out.println(a);
  }
}
}

class MyNative {
public native int cubecal(int x);
static {
  System.loadLibrary("mynative");
}
}

2. Generate the MyNative.h for call native functions

javac JNITest.java

javah -jni MyNative

3. The native code

Note: the file name should be an .c file.

According to MyNative.h:

#include "jni.h"

int cube(int x) {
  return (x*x*x);
}

JNIEXPORT jint JNICALL Java_mynative_cubecal
(JNIEnv *e, jobject o, jint x) {
  return cube(x);
}

4. Configure dependencies in MS visual studio

Put ‘$JAVA_HOME$/include/jni.h’ ‘$JAVA_HOME$/include/win32/jni_md.h’
and ‘MyNative.h’ to the project directory in VS2008

5. Build mynative.dll

Just follow MS Visual Studio’s method.

6. Copy mynative.dll to the directory where the Java project is in.

The directory is like this:

2008-06-02  14:52               413 mynative.class
2008-06-02  14:52               719 JNITest.class
2008-06-02  15:39             7,168 mynative.dll

7. Run the Java program:

java JNITest 9

729

The cubical computation is done by the function from the C library correctly.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *