An introduction to native backed objects with the Android NDK

As many Android developers know the Android NDK is used to cross-compile native (C/C++) code to run in Android programs. Unfortunately, because it uses JNI we’re limited to a C-style call interface. Tools like SWIG can be used to automatically generate wrappers for existing code including C++ classes. In this post I’ll provide an introduction to native backed objects in Java, which are objects whose implementation/resources are primarily implemented in a native language. I won’t be using SWIG since it might muddle everything a bit because of what it takes to get it to wrap standard library classes on the NDK.

What are we trying to accomplish? Our goal here is to have the ability to write Java code that operates on normal Java objects, but underneath all of the “magic” is happening in C/C++ land. There are two main use cases for this: speed-ups from using faster native code for memory intensive/processor intensive operations, and for leveraging existing code bases into a new Android project. Especially in the second case, native backed objects give you the ability to write UI code for a new Android project that uses your existing C++ classes as the main base of functionality; we simply create “wrapper” classes that can be used in Java land the same way you’ve been using them in C++ land, but now have the added benefit of being directly¬†inter-operable¬†with the Android framework. Continue reading “An introduction to native backed objects with the Android NDK”