How to pass an object or delegate using JNI/Kotlin callback?

  android, android-ndk, c++, java-native-interface, kotlin

I’m new to JNI development. What I’m trying to achieve is that I need to capture a snapshot using JNI. I’m able to achieve the same using Kotlin/Java.

I’m using the following code to capture the snapshot and copy it into a bitmap.

            jclass bitmapConfig = env->FindClass("android/graphics/Bitmap$Config");
            jfieldID rgba8888FieldID = env->GetStaticFieldID(bitmapConfig, "ARGB_8888", "Landroid/graphics/Bitmap$Config;");
            jobject rgba8888Obj = env->GetStaticObjectField(bitmapConfig, rgba8888FieldID);

            jclass bitmapClass = env->FindClass("android/graphics/Bitmap");
            jmethodID createBitmapMethodID = env->GetStaticMethodID(bitmapClass,"createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
            jobject bitmapObj = env->CallStaticObjectMethod(bitmapClass, createBitmapMethodID, SNAPSHOT_WIDTH, SNAPSHOT_HEIGHT, rgba8888Obj);

            jintArray pixels = env->NewIntArray(SNAPSHOT_WIDTH * SNAPSHOT_HEIGHT);
            jmethodID setPixelsMid = env->GetMethodID(bitmapClass, "setPixels", "([IIIIIII)V");
            env->CallVoidMethod(bitmapObj, setPixelsMid, pixels, 0, SNAPSHOT_WIDTH, 0, 0, SNAPSHOT_WIDTH, SNAPSHOT_HEIGHT);

Next, I need to update my Kotlin class that this bitmap has been created and pass this bitmap object as a callback. I’m able to pass a string using the Kotlin/JNI callback implementation.

My code for Kotlin/JNI callback ( String )

jclass cls = env->GetObjectClass(clazz);
jmethodID methodid = env->GetMethodID(cls, "RegisterCallback", "(Ljava/lang/String;)V");
jstring jstr = env->NewStringUTF("Hello from C");
env->CallVoidMethod(clazz, methodid, jstr);

Function in the Kotlin side,

fun RegisterCallback(success: String) {
    onBitmapReceived?.invoke(success)
}

Now, I would like to know is it possible to pass a Bitmap like this? Or, even better pass a delegate or something.

Thanks in advance.

Source: Windows Questions C++

LEAVE A COMMENT