Easy Start with JNA

JNA (Java Native Access) is the good and easy answer to the JNI(Java Native Interface). Those who find it cumbersome to to call C, C++ DLL functions using JNI, then JNA is for you. The project is hosted at https://jna.dev.java.net/ .

Here is my first encounter(experiment) with the JNA.

Problem: I want to call one DLL function in Java program

Solution: The first thing that comes into my mind is JNI, coz I heard a lot about it whenever something "native" has to be called in Java. Just while surfing for the more information on basic JNI programming, I came across the JNA project/api and find it interesting to give it try.

Here are the basic two things you need to have in order to use JNA
1) JNA api JAR file (jna.jar):
Download it from here

2) DLL which you want to call in your Java program
Now this may be the big thing for a guy who haven't worked on VC++, DLL, MFC etc things. So here is the quick link about how to create the DLL
http://www.icynorth.com/development/createdlltutorial.html

This is the best about JNA, you don't need to write header file as that we need to do in JNI

JAVA Code

import com.sun.jna.*;
import com.sun.jna.ptr.*;
/** Simple example of JNA interface mapping and usage. */
public class HelloWorld {
// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.
public interface TestLibrary extends Library {
TestLibrary INSTANCE = (TestLibrary)
Native.loadLibrary("TestDLL", TestLibrary.class);
// Call C/c++ function
void helloWorld(int n);
}

public static void main(String[] args) {
int n = TestLibrary.INSTANCE.helloWorld(1);
}
}

C/C++ Code

extern "C" __declspec(dllexport) int helloWorld (int divider)
{
return 77/divider;
}

Comments

Popular Posts