JVM在attachCurrentThread JNI回调调用时崩溃

时间:2014-10-31 14:37:09

标签: java c callback java-native-interface

希望你做得很好。

我在C中有一个JNI实现,其中C函数附加到当前JVM线程并回调Java方法,这实际上是在attachCurrentThread()函数调用时崩溃JVM。 我的实施基于链接Keeping a global reference to the JNIEnv environment

中给出的答案

线程创建部分,它将侦听套接字连接以接受事件并注入GetEvent函数。

// create thread for reading from socket.
        pthread_attr_init(&plafParams->readThreadAttr);
        pthread_attr_setdetachstate(&plafParams->readThreadAttr, PTHREAD_CREATE_JOINABLE);
        pthread_attr_setstacksize(&plafParams->readThreadAttr, 16384);
        plafParams->eventThreadFlag = 2;
        if(pthread_create(&plafParams->hReadThread_p, &plafParams->readThreadAttr, ( void * ) plafIncomingPortReadThread, ( void * ) dlmsInstance))
        {

            plafFree(plafParams);
            return FAILURE;
        }

        //create thread to read from platform (to monitor wrapperRecv() process)
        pthread_attr_init(&plafParams->EventthreadAttr);
        pthread_attr_setdetachstate(&plafParams->EventthreadAttr, PTHREAD_CREATE_JOINABLE);
        pthread_attr_setstacksize(&plafParams->EventthreadAttr, 16384);

        if( pthread_create(&plafParams->EventThreadHandle_p, &plafParams->EventthreadAttr, ( void * ) IncomingPortEventReadHandling, ( void * ) dlmsInstance))
        {
            pthread_attr_destroy(&plafParams->readThreadAttr);
            plafParams->eventThreadFlag = 0;
            return FAILURE;
        }



static JavaVM *jvm;

// Caching the JVM on JVM OnLoad
jint JNI_OnLoad(JavaVM* vm, void* reserved) 
{
    JNIEnv* jenv;
    version = (*vm)->GetEnv(vm, (void **) &jenv, JNI_VERSION_1_6);
    jvm = vm;
    printf("\n jvm = %d \n",rs);
    if(rs == JNI_OK) {
        printf("\n JNI_OK \n");
    }
}

回调功能

void GetEvent(unsigned char *msg)
    {

        printf("\n Processing event data \n");
        JNIEnv *env;

        printf("\n Before attaching JVM thread \n");
        jint rs = (*jvm)->AttachCurrentThread(jvm, &env, NULL); // JVM crashes here, tried with jint rs = (*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL), nothing helps
        printf("\n After attaching JVM thread \n");

    }

在接收到事件时执行GetEvent(),我的JVM在AttachCurrentThread()函数调用时崩溃。 有人可以帮我确定问题吗? 在此先感谢,任何建议将不胜感激。

的问候,

Saravanan G

1 个答案:

答案 0 :(得分:0)

我猜你的线程已经可以附加到VM,因此不需要AttachCurrentThread。也许您只需要像这样检查线程状态:

How to obtain JNI interface pointer (JNIEnv *) for asynchronous calls