简体   繁体   中英

JNI calling a Java Method from C++

I am having a problem with JNI, calling a method from C++ to Java.

I am trying to call a void method that takes a boolean. My java code is the following:

public void setStatus(boolean bool) {
    // Do stuff...
}

public native void initialize(int defaultPort);

In my C++ code, I am making a struct to hold the env and object and pass it to a thread:

JNIEXPORT void JNICALL Java_com_device_client_HostConnection_initialize
  (JNIEnv * env, jobject obj, jint port)
{
    struct javaInfo* data = (struct javaInfo*) malloc(sizeof(struct javaInfo));
    data->env = env;
    data->javaObjHost = obj;

    pthread_t pth;
    pthread_create(&pth, NULL, startServer, (void *) data);

    free(data);
}

In the actual function, I am trying to obtain the class and then the MethodID and then call the void method, as follows:

void *startServer(void* arg) {
    struct javaInfo* data = (struct javaInfo*) arg; 
    JNIEnv* env = data->env;
    jobject javaObjHost = data->javaObjHost;

    cls = env->GetObjectClass(javaObjHost);
    mid = env->GetMethodID(cls, "setStatus", "(Z)V");
    if (mid == 0) {
        exit(-1);
    }
    env->CallVoidMethod(javaObjHost, mid, true);
}

It is hard for me to debug with JNI. I have tried putting a breakpoint in Eclipse in setStatus() but it never gets called. exit() is not called as well. The programs stomps for a second or two, then continues. I am not sure what is going on.

Could anyone please help me?

Thank you very much.

You cannot pass env pointers to other threads. You need to join the thread to the JVM.

In the original thread, called GetJavaVM to obtain a JavaVM pointer:

JavaVM *vm = 0;
env->GetJavaVM(&vm);

Then in the other thread, attach the VM to that thread and get a new env pointer:

vm->AttachCurrentThread(&env, 0);

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