How to use JNI to call a native DLL from a Java program - MDHSRobotics/TeamWiki GitHub Wiki
#How to use JNI to call a native DLL from a Java program
There are several good online sources that will explain how this can be done. I based this overview on the following sources:
The purpose of JNI is to enable a java program to use native libraries. Since many advanced libraries, including our Zed SDK, are only available in C++ native shared libraries, but we program our robot in Java, it is at times necessary to use JNI.
###Best Practice The best practice is to write a thin C++ wrapper library to handle the interface to the native library. The java code links to this wrapper library . The wrapper library then uses the native libraries. This is an application or encapsulation and decouples our Java code from any specific native library, making it easier to make changes in the future.
###Approach This tutorial assumes you are familiar with how to create Java classes and have some basic programming experience. Refer to the other team tutorials, the references listed above and in the References section of the Wiki if you need additional information.
-
Create the java class that will interact with the native wrapper library. This class declares native method signatures to indicate to the compiler which methods will be handled by the native library rather than implemented in Java. In hte following example, a class declares a method transformImage as a native method.
private native void transformImage();
1. Load the library into Java using the System loadLibrary() method. This is typically accomplished in a static block at the top of the class. Notice that the file extension of the native library is not specified. In windows, the library will typically be .dll, in Unix and Linux, it will typically be .so and on Macs it will typically be .dylib
```java
static { System.loadLibrary("hello");}
-
Compile your java code. In Eclipse, this is typically done by simply saving the class.
-
Compile your native headers. If you wish to run javah from within eclipse, follow this guide. Otherwise, do it from the command line. This will generate a c++ header (.h) file.
-
Implement and compile the c++ wrapper library. You must include the generated jni header file and implement the method(s) specified within the header.
-
Configure your java runtime environment to include the directory of the shared library:
-Djava.library.path="_path-to-your-library_"