Getting Started with JNI on Android, Windows and Mac
Java Native Interface (JNI) is the glue between Java and native code such as C, C++, and assembly. With JNI, Java applications are capable of supporting platform-specific features. JNI enables developers to call low-level APIs (e.g. SQL, OpenGL etc.) to make Java application more powerful with higher performance. For example, we can download a JDBC driver, and unzip the jar package to take an insight. The driver is not written in pure Java. It also contains native libraries for Linux, Mac, and Windows.
Since JNI is so useful, I’d like to share how to get started with JNI on Android, Windows, and Mac.
JNI on Android
Download NDK and configure the location in Eclipse:
Create a new project named hellojni. To automatically generate the native C/C++ code and configuration file, you just need to right-click on your project and select Add Native Support:
After that, a JNI project will be automatically generated. To build the shared library, you just need to implement JNI methods in C/C++, and add configurations in Android.mk.
When you save all changes, the shared library libhellojni.so will be automatically generated. You can also build the library by typing in ndk-build.
JNI on Windows
Create a Win32 project named hellojni in Visual Studio:
Select DLL as the application type:
Configure headers and libraries:
Write the JNI code, and build the hellojni.dll:
JNI on Mac OS X
Create a Library project named hellojni in Xcode:
Select STL as the framework:
In build settings, configure the paths of JavaVM headers and JavaVM libraries:
Write the JNI code, and build the libhellojni.dylib:
How to Use the JNI Shared Library
Declare the native methods in Java:
public native String stringFromJNI();
public native static void nativePrint();
Load the shared library in Java:
static {
System.loadLibrary("hellojni");
}