Previous Article we saw how kotlin interacts with cpp in a simple Hello World application. We learned the basic changes to make in the
CMake and the
gradle file, we also looked at how to call native code from Kotlin.
In this article, we are going to find out how to call Kotlin from native code.
Do we really need to call kotlin code from native?
The first question that comes to mind when working with Kotlin and Android NDK is, do we really need to call Kotlin code for the native c/cpp code?
The answer is yes!!! For example, when using FFmpeg to decode video frames we need callbacks to retrieve the result from the native code. We can get the callbacks in the form of some progress which can be used to update the UI.This helps in keeping the UI interactive during some CPU intensive operations.
How to do it?
This is the very next question that came to my mind 🤔. Well before going to the sample on how it’s done, lets see what all the methods and properties available to us.
Static Properties and Methods
JniEnv has different methods to access value of static fields.
Let’s take the example of the
NativeStore class we created in previous article, which is a wrapper around native functions.
Accessing a static field
Here we created a
booleanField variable inside the companion object. Accessing the
Boolean value in the native code can be done as:
To get the Id of the static field we used the function
Accessing a static method
Similarly to accessing the static fields we can access a static methods from the native code. To get the Id of static method we use
jmethodID GetStaticMethodID(JNIEnv *env, jclass class,const char *name, const char *sig) function.
functions which call static methods
JEnv methods to call static methods from native code
Native Store code, we can add a function that returns the sum of two values passed to it.
Instance’s Properties and Methods
Similarly to the previous examples we can use the Instance Properties and Methods.
In this article we saw how we can call methods in kotlin directly in the cpp code. This knowledge can be extended to creating callbacks, such as updating UI about some video/audio processing through ffmpeg etc. If you liked this post, hit 👏 .
You might have noticed the “Z” in function
getStaticFieldId , those are the type signatures used in native code.
originally posted in Medium