3

I'm working JNI and I wonder is it possible to communicate via delegate.

for example:

Kotlin

typealias MessageReceived = (msg: String) -> Unit

external fun RegisterCallback(callback: MessageReceived)


C++ (JNI)

JNIEXPORT void Java_some_package_name_Foo_RegisterCallback(JNIEnv* env, jobject, void (*MessageReceived)(jstring msg)) {
    if (MessageReceived != nullptr) {
        char buffer[260] = {0};
        sprintf(buffer, "Callback registered!");
        jstring messageJStr = env->NewStringUTF(buffer);
        MessageReceived(messageJStr);
        env->DeleteLocalRef(messageJStr);
    }
}

is it impossible?

When I ran this code, I can't access and get SIGSEGV (address access protected).

I found this, but it seems to complicated to me.

Thank you for your interest

SlaneR
  • 684
  • 5
  • 19

1 Answers1

2

Yes it is possible.

Type of your MessageReceived should be jobject.

To invoke delegate you need:

  • find MessageReceived class by GetObjectClass
  • find method (I'm not sure what is method name here) by GetMethodID
  • invoke it using CallVoidMethod

You can find example here

talex
  • 17,973
  • 3
  • 29
  • 66
  • I mean, without jmethodID or something. – SlaneR Nov 28 '18 at 06:24
  • 1
    You can't call java method without "jmethodID or something" :) – talex Nov 28 '18 at 06:25
  • I also found about `CallXXXMethod`, but it should be target method defined in native call wrapping class. I wonder is it possible to invoke delegate by passing it. Sorry for my bad English. – SlaneR Nov 28 '18 at 06:25
  • All `CallXXXMethod` work the same way. Only difference is type of called method. – talex Nov 28 '18 at 06:28