SlaneR
SlaneR

Reputation: 714

JNI/Kotlin: Is it possible to pass delegate to JNI?

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

Upvotes: 3

Views: 770

Answers (1)

talex
talex

Reputation: 20436

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

Upvotes: 2

Related Questions