Search code examples
javaandroidc++apijava-native-interface

How to create a Java Library (API) with native code via JNI


My problem is as follows.

I need to create a library in Java. So far so good. Like any decent Java Libraries, it must be usable on any JVM.

But the difficulty here is that this library will contain a lot of native code.

I have some knowledge in JNI. I've tried creating a few native methods in Java in an Android application with Android Studio and with the Android NDK.

That's great I can do a lot of HelloWorld examples. But how can I export this as a library ?

My project needs external C++ Libraries. I would like to wrap these libraries and use them in a JNI wrapper wrapped inside a Java Library.

See the following schema : Java JNI API Schema

To make things even simpler, take a simple HelloWorld JNI API for example. Create a Java Desktop App (or anything else). Import the Helloworld JNI API (as jar), call String HelloWorldJNI_API.sayHello(String yourName) and print the result.

What is required here :

  1. The JNI API will obviously declare the sayHello() method as a native method ;
  2. The argument (String yourName) is sent to JNI ;
  3. The JNI code calls an internal awesome C++ so library that crunches the data and returns a "hello" + "yourName" (awesome, right ?)
  4. The JNI code returns the result as a jstring
  5. Finally, the Java API returns the result as a String and voila !

This simple example should show you what I am trying to do.


Solution

  • Well, your Library will contain both the .jar file with the java wrapper code as well as the native files (.so if you're on linux based, or .dll if you're on windows).

    Here's where the fun begins :

    Because native is compiled in processor assembly language you will have to compile the .so for all your supported target (eg for all android with native support since like forever): armv5, armv7, armv7s , arm64

    Now, you will have to provide an archive with all the above.

    This is the case where you want a stand alone library, without providing the code to the developer.

    If you can provide the code,then you don't need to worry about different architectures.