Understanding Android NDK with Kotlin: Episode 2 — Callbacks(kotlin to cpp)

Nitish Bhatt
Fueled Engineering
Published in
2 min readJun 11, 2018

Previous article was mostly about the theoretical concepts that comes handy when working with the Android NDK.

In this article we are going to see how we can call native code from kotlin.

I created a KotlinJniSample Application that has a simple HelloWorld example to showcase how native code is called from kotlin.

I created a class NativeStore to encapsulate the native methods.

Store for native methods

The definition of the native function stringFromJNI() is available in native-lib.cpp file

and the MainActivity Class where we show TextView with text from the native code( A little DI magic can also be added to extract the initialization ).

Now that we have everything ready its time to take a look at our CMakeLists.txt and gradle file.

CMake Configuration

Although Android creates the CMake file for us with all the relevant functions, a little information comes in handy if we change the library name or so.

In the CMakeLists.txt file:add_library function is used to add the path to the source code(in our case native-lib.cpp).

There are a lot of CMake functions at our disposal.Let’s look at some of the core functions from the configuration:

  • add_library: creates and names a library, sets it to either STATIC or SHARED, and provides the relative paths to its source code.
add_library
  • find_library: searches for a specified pre-built library and stores the path as a variable.
find_library
  • target_link_libraries: is used to specify libraries CMake should link to your target libraries that were created by add_library.
target_link_libraries

Gradle Configuration

This part is handled in Android by default. We see a path to the CMakeLists.txt and cpp flags added to the gradle file.

Now that we have everything ready, we are good to run the app using NDK 🙌😎

Conclusion

In this article we saw how to create a simple APP using kotlin and NDK. If you liked this post, hit 👏 . Do hop in for the Episode-3 where we will see how to use callbacks from c++ to Kotlin.

TL;DR

  1. we use init block of companion object instead of static block
  2. We use external keyword instead of native .
  3. Link to the source code.

Catch me here:
Twitter: @iamnitishbhatt
LinkedIn:
https://www.linkedin.com/in/iamnitishbhatt/
Github: https://github.com/initishbhatt

--

--