本文介绍了如何获取异步调用JNI接口指针(JNIEnv的*)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经了解到,JNI接口指针(JNIEnv的*)仅在当前线程有效。假设我开始了一个本地方法中一个新的线程;如何可以异步事件发送到Java方法?作为这种新的线程不能有(JNIEnv的*)的一个参考。对于存储(JNIEnv的*)一个全局变量显然是行不通的?

I have learned that the JNI interface pointer (JNIEnv *) is only valid in the current thread. Suppose I started a new thread inside a native method; how it can asynchronously send events to a Java method? As this new thread can't have a reference of (JNIEnv *). Storing a global variable for (JNIEnv *) apparently will not work?

推荐答案

这是怎么我用它在过去,看到我的

This is how I've used it in the past, see my blog

由于回调是另一个线程虚拟机上下文必须附加到当前线程。一旦附着的方法可以被调用

Since the callback is on another thread the VM context must be attached to the current thread. Once attached the method can be called.

void callback(int val) {
    JNIEnv * g_env;
    // double check it's all ok
    int getEnvStat = g_vm->GetEnv((void **)&g_env, JNI_VERSION_1_6);
    if (getEnvStat == JNI_EDETACHED) {
        std::cout << "GetEnv: not attached" << std::endl;
        if (g_vm->AttachCurrentThread((void **) &g_env, NULL) != 0) {
            std::cout << "Failed to attach" << std::endl;
        }
    } else if (getEnvStat == JNI_OK) {
        //
    } else if (getEnvStat == JNI_EVERSION) {
        std::cout << "GetEnv: version not supported" << std::endl;
    }

    g_env->CallVoidMethod(g_obj, g_mid, val);

    if (g_env->ExceptionCheck()) {
        g_env->ExceptionDescribe();
    }

    g_vm->DetachCurrentThread();
}

这篇关于如何获取异步调用JNI接口指针(JNIEnv的*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-21 16:49