Callback from c++ to Kotlin using JNI : Android

Viewed 776

Is there a way to call a Kotlin function directly from c++ in regular time intervals? Im new to JNI and most questions in stack overflow related to this involves a JNIEnv obj, but to access this object I'd have to create an external function in MainActivity and trigger it in the Kotlin world.

Here's a dummy code of the objective.

Main Activity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        performComputation();
    }

    external fun stringFromJNI(): String // The default method that retrieves a string

    external fun performComputation(); 


    fun updateUI(someValue: Int){
    // Code to Update UI. This method must be called from C++ in regular intervals
   
    } 

    companion object {
        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("native-lib")
        }
    }
}

Native-lib.cpp

#include <jni.h>
#include <string>
#include "staticClass.h"

extern "C" JNIEXPORT void JNICALL
Java_com_twrotu_testapplication_MainActivity_performComputation(
        JNIEnv* env,
        jobject) {
    accumulate();
}

StaticClass.h

#ifndef TEST_APPLICATION_STATICCLASS_H
#define TEST_APPLICATION_STATICCLASS_H

int num1 = 5;
int num2 = 10;

void accumulate(){
    while (num1 <= 100){
        num1 += num2;
        if (num1%2 == 0 ){
            // Trigger a Java Method and Update UI whenever num1 is even

        }
    }
}

#endif //TEST_APPLICATION_STATICCLASS_H

Ideally I will be able to trigger the Kotlin Method everytime Num1 from Static.h is even in the accumulate() function. Is this possible ? If yes please do share useful resources and give me some insights as to how I must approach this problem. I was able to find many resources using google but I wasn't able to understand it properly.

TIA.

1 Answers

You can use inheritance and from C++ class to Kotlin class and a pointer in C++ to call the virtual function which intern call your function

Th famous SWIG Tool offers such a functionality, I have an Example Kotlin SWIG JNI Inheritance and Callback in github,

What it does is, it calles a virtual function as below

void jniexample::Caller::call() { 
    if (_callback) { 
        _callback->run();
    } 
}

the run() is a virtual function as below

namespace jniexample {
    class Callback {
        public:
        virtual void JNIEXAMPLE_EXPORT_FUNC run();

While calling SWIG command we pass the -directors which auto stubs the callback

and in the Kotlin code

var callback = KotlinCallback()
var caller = Caller()
caller.setCallback(callback)
caller.call()
caller.delCallback()

Here the caller.call() will call the KotlinCallback class from the C++ pointer

Related