基于缓存的job对象从本机函数调用Java函数,methodID失败



Java源码:

public void onEventListener(final int eventID, final int arg1,
            final long arg2, final String message) 
{
     Log.d("TEST", "onEventListener() is called - eventID = "+eventID);
}

JNI代码:

JavaVM* gJvm = NULL;
pid_t _vm_tid = -1;
JNIEnv * jEnv = NULL;
jclass native_cls_id = NULL;
jmethodID _onEventListenerID=NULL;
jobject m_nativeObj = NULL;
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
        ....
    gJvm = vm;
    _vm_tid = gettid();
        ....
}

//功能
void NotifyFromNative(int eventID, int arg1, long arg2, char* message) {
    LOGD("Receive_Message_Callback is called - eventID = %d",eventID);
    JNIEnv* env = NULL;
    pid_t tid = gettid();
    LOGD("Step 0");
    if (tid != _vm_tid) {
        jint ret = gJvm->AttachCurrentThread(&env, NULL);
        LOGD("Step 1 - tid != _vm_tid ret=%d",ret);
    } else {
        LOGD("Step 1 - tid == _vm_tid");
        gJvm->GetEnv((void**) &env, JNI_VERSION_1_4);
    }
    LOGD("Step 2");
    jstring jstr = env->NewStringUTF(message);
    LOGD("Step 3");
    env->CallVoidMethod(m_nativeObj, _onEventListenerID, eventID, arg1, arg2,
            jstr);
    LOGD("Step 4");
    env->DeleteLocalRef(jstr);
    if (tid != _vm_tid)
        gJvm->DetachCurrentThread();
}

//初始化JNI函数

JNIEXPORT jint JNICALL Java_NativeManager_initialize(JNIEnv * env,
        jobject obj) {
    LOG_UI("Native initialize is called");
    m_nativeObj = env->NewGlobalRef(obj);
    jclass cls = env->FindClass(classPathName);
    if (cls == NULL) {
        LOGE("Can't find class %s", classPathName);
        return 0;
    }
    native_cls_id = (jclass) env->NewGlobalRef(cls);
    _onEventListenerID = env->GetMethodID(native_cls_id, "onEventListener",
                "(IIJLjava/lang/String;)V");
    if (!_onEventListenerID)
        {
         LOGE("Can't find onEventListener Java method");
             return 0;
    }   
        char* message = "test";
    jstring jstr = env->NewStringUTF(message);
        env->CallVoidMethod(m_nativeObj, _onEventListenerID, 1, 1, 1,
                jstr); //This call work well
    NotifyFromNative(0, 1, 1, "test"); //<= problem here
}

<

Logcat消息/strong>

onEventListener() is called - eventID = 1 
Receive_Message_Callback is called - eventID = 0
Step 0
Step 1 - tid == _vm_tid
Step 2
Step 3 
W/dalvikvm(2160): Invalid indirect reference 0x576725d0 in decodeIndirectRef
E/dalvikvm(2160): VM aborting
A/libc(2160): Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 2160 ()

问题:

有谁能为我解释为什么调用NotifyFromNative(0,1,1,"test")有问题,尽管创建了对象的全局引用。非常感谢

我发现Android JNI函数不能使用Long参数。因此,我将长值分解为2个整数值,代码现在正在工作。

这是我偶然发现的一个很老的问题。但目前的答案是错误的。问题在这里

void NotifyFromNative(int eventID, int arg1, long arg2, char* message) {

应该是

void NotifyFromNative(int eventID, int arg1, jlong arg2, char* message) {

注意jlong。Java中的Long是64位的。c/c++中的Long不能保证是这个大小。Jlong确保java中的long类型兼容。

最新更新