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.

jdbc

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:

android JNI

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:

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.

jni_folder

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.ndk_build

JNI on Windows

Create a Win32 project named hellojni in Visual Studio:

win32_project

Select DLL as the application type:

type_DLL

Configure headers and libraries:

build_configuration

Write the JNI code, and build the hellojni.dll:win32_src

JNI on Mac OS X

Create a Library project named hellojni in Xcode:

mac_library_project

Select STL as the framework:

mac_framework_selection

In build settings, configure the paths of JavaVM headers and JavaVM libraries:

mac_java_headersmac_java_libs

Write the JNI code, and build the libhellojni.dylib:

mac_jni_code

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");
}

Source Code

https://github.com/yushulx/JNI-

Search Blog Posts