0

i encounter a issue that how to callback java method in C method, this c method unlike JNI generate c method. not include JNIEnv and JObject parameter in the parameter list. How to solve it or something else workaround....

0

2 Answers 2

1

To execute a Java method from C program you need to load JVM into C program first. For that you should use the Invocation API, see http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/invocation.html

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I can second that: I have code in production that does exactly this.
Yes, i know that way. But this C code compiled by NDK, it throws undefined reference to 'JNI_CreateJavaVM'.
0

This method will create its own JNI_CreateJavaVM method and attach it as a thread then releases it right after using it.

Load jvm.dll installed in your computer

TCHAR* dllpath = (char*)TEXT("C:\\Program Files\\Java\\jdk1.8.0_65\\jre\\bin\\server\\jvm.dll");
HMODULE jniModule = LoadLibrary(dllpath);

Define the function to create JVM

typedef int (JNICALL * JNI_CreateJavaVM)(JavaVM** jvm, JNIEnv** env, JavaVMInitArgs* initargs);
JNI_CreateJavaVM createJavaVM = (JNI_CreateJavaVM)GetProcAddress(jniModule, "JNI_CreateJavaVM");

Create the JVM

JavaVMOption* options = new JavaVMOption[1];
options[0].optionString = const_cast<char*>("-Djava.class.path=" USER_CLASSPATH);

JavaVMInitArgs initArgs;
initArgs.version = JNI_VERSION_1_6;
initArgs.nOptions = 1;
initArgs.options = options;
JavaVM* jvm;
JNIEnv* env;
DWORD retval;
if ((retval = createJavaVM(&jvm, &env, &initArgs)) != JNI_OK){
    cout << "beyond the scope of this answer" << endl;
    return 1;
}
jint retvalue = jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
bool mustDetach = false;

Detach your JVM if necessary

if (retvalue == JNI_EDETACHED)
    {
        JavaVMAttachArgs args;
        args.version = JNI_VERSION_1_6;
        args.name = NULL;
        args.group = NULL;
        retvalue = jvm->AttachCurrentThread((void**)&env, &args);
        mustDetach = true; // to clean up afterwards
    }

Point to your target Java class where the method is located

jclass clazz = env->FindClass("MyClazz");

Point to the java method

jmethodID mid = env->GetStaticMethodID(clazz, "myJavaMethod", "()I");

Invoke the java method

int returnedValue = env->CallStaticintMethod(clazz, mid);

cout << "Returned value is " << returnedValue->size << endl;

This will not throw undefined reference to JNI_CreateJavaVM

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.