简体   繁体   中英

Invoking native methods from JAVA when creating the JVM from C++?

I have a situation of a C++ executable which creates a JVM using JNI_CreateJavaVM , and that java method wants to invoke a native method back:

//In Java:
private native void myNativeMethod();

//In C++:
JNIEXPORT void JNICALL
Java_SomeClass_myNativeMethod(JNIEnv *env, jobject instance) {
..
}

But it doesn't work (linking error).

BUT, if I move the method into a c++ library and load the library from Java using System.loadLibrary, it does work.

Any way of enabling this behaviour with only a c++ executable without going through the trouble of having 3 pieces (main c++ executable => starting a JVM and running a jar => loading a c++ library) but instead keeping it at two?

Thanks!

When loading a native library in Java using System.loadLibrary , it is stored internally in a list that is attached to the current ClassLoader , and then this list of libraries is searched when looking up the native method. So, it will indeed not see the native method you have defined in the same executable.

You should be able to make this work using the RegisterNatives JNI API, which allows explicitly registering native functions for a particular class as pointers.

JNIEnv env = ...
jclass cSomeClass = env->FindClass("SomeClass");
JNINativeMethod natives[] = {
  {(char*) "myNativeMethod", (char*) "()V", (void*) &Java_SomeClass_myNativeMethod},
};
env->RegisterNatives(cSomeClass, natives, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM