JNI: Callback from JVM to C++ fails to run

和自甴很熟 提交于 2020-01-03 02:38:45

问题


I start JVM from C++ program.

C++ code:

JNIEXPORT jobject JNICALL com_javelin_JavelinMarketData_callBackIntoNative(JNIEnv* env, jobject obj, jlong ptr)
{
        std::cout << "com_javelin_JavelinMarketData_callBackIntoNative called" << std::endl;
}

int main()
{
       JavaVM* jvm;
       JNIEnv* env;
       ...
       JNI_CreateJavaVM(&jvm, (void **)&env, &args);
       jmethodID mainMethod =  env->GetStaticMethodID(helloWorldClass, "main", "([Ljava/lang/String;)V");
       env->CallStaticVoidMethod(helloWorldClass, mainMethod, ...);
}

then I need my C++ function called back from java:

Java code:

native void callBackIntoNative(long ptr);

public void onResponse(long param)
{
    System.out.println("Calling callBackIntoNative()");
    callBackIntoNative(param); 
}

When I run my C++ program, JVM starts correctly, but after it prints "Calling callBackIntoNative()" the following acception appears:

Exception during callBackIntoNative(): 'com.javelin.JavelinMarketData.callBackIntoNative(J)V'
java.lang.UnsatisfiedLinkError: com.javelin.JavelinMarketData.callBackIntoNative(J)V

Can you please help?


回答1:


Thanks, but I found a solution: I should have registered my C++ function as a native method using the code:

const JNINativeMethod methods[] = { { "callBackIntoNative", "(J)V", (void*)&com_javelin_JavelinMarketData_callBackIntoNative } };

const int methods_size = sizeof(methods) / sizeof(methods[0]);

jclass jClass = env->FindClass("com/javelin/JavelinMarketData");

env->RegisterNatives(jClass, methods, methods_size);

Now it works fine.




回答2:


I would compile your callback apart into a dynamic library (.dll, .so, whatever your OS) and put it accesible to your java program. Then you just load your library by using JNI and call from your java classes whatever functionality you have in the library.



来源:https://stackoverflow.com/questions/21734086/jni-callback-from-jvm-to-c-fails-to-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!