2

I use JNI in my Java code to call native C code. This works fine and I'm doing some processing in the C code. The C code registers an event listener so that I'm notified every time a new result is ready in the C part.

Now I want to return the results to the Java code like that:

void notifyGazeEvent()
{
    jclass cls = (*env)->GetObjectClass(env, obj);
    jmethodID mid = (*env)->GetMethodID(env, cls, "newGazeEvent", "(I)V");
    if (mid == 0)
    {
        return; 
    }
    printf("In C, about to enter Java");
    (*env)->CallVoidMethod(env, obj, mid, 1);
}

The problem now is: I don't know where to get the JNIEnv object and the jObject object from. This is passed when I first call the C code:

JNIEXPORT void JNICALL
Java_a_b_C_doCalculation(JNIEnv *env, jobject obj)
{
// here I register all the handlers etc, 
}

But I don't know how I can pass the references until my method that does the callback to Java.

1

1 Answer 1

1

To keep the jobject obj outside the Java_a_b_C_doCalculation function, you have to create a global reference, since all objects (JNIEnv also) are no longer valid after the function returns. A global reference can easily be created with NewGlobalRef.

The JNIEnv pointer can't be saved that way, also if the thread that calls notifyGazeEvent() was created in C you have to attach the thread to the JVM first. Save the JavaVM *vm pointer from JNI_OnLoad, and either optain the JNIEnv with GetEnv or attach a newly created thread with AttachCurrentThread (AsDaemon).

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

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.