Friday, December 25, 2015

Java Native Interface

JNI supports two way interaction between Java and other languages, such as C++, C, Assembly.

Here I describe how to use JNI for Java/C++ 2-way Calls:
 1) Create a Java Project with with native methods.
     run "javah -jni MyExample" to generate MyExample.h

 2) Create a C++ DLL Project with MyDLL.cpp(#include "MyExample.h")
     In Project Properties, add Additional Include Directories:

 3) In Java project, add MyDLL.dll to Native Library Location.
     In Java code, add System.loadLibrary("MyDLL");

Note: A common run-time error when using JNI is java.lang.UnsatisfiedLinkError, which may be caused by 32-bit/64-bit DLL version mismatch or function signature mismatch. Here is a few tips to deal with this issue.
  • 64-bit JDKs usually work with 64-bit DLLs, while 32-bit JDKs work with 32-bit DLLs.
    Although java provides options -d32 or -d64, it's not always working.
  • To check if a DLL is a 32-bit, run "vcvarsall.bat amd64" and
    "dumpbin.exe \headers MyDLL.dll" 
  • One code base can support both 32-bit and 64-bit platforms.
The tools used in the above discussion: Java 1.7+, Eclipse(Mars) for Java, VC++(2013) for C++.

For best practice of using JNI, I recommend one article on IBM website: "Techniques and tools for averting the 10 most common JNI programming mistakes".

Note: Java is newer than C++, but they are influencing each other since the beginning. Wikipedia provides an excellent comparison of the big two, here is the link.

No comments:

Post a Comment