Reputation: 1681
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!
Upvotes: 0
Views: 101
Reputation: 33845
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);
Upvotes: 1