2013-04-11 78 views
0

问题是要找出哪些Java函数调用某个JNI函数。在Java中,这将通过new Exception.printStackTrace()来实现,但这必须通过本地(JNI)函数完成。从JNI调用exception.printStackTrace()

因为稍后找到自己的代码最简单的方法是在'网络中发布它,我发布了问题和答案。

回答

3

new Exception.printStackTrace()的JNI类似物是:

//#include <android/log.h> 
//#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "~~~~~~", __VA_ARGS__) 
//#define DLOG(...) __android_log_print(ANDROID_LOG_DEBUG , "~~~~~~", __VA_ARGS__) 
void printStackTrace(JNIEnv *env) { 
LOGD("###################################################################################printStackTrace{"); 
    jclass cls = env->FindClass("java/lang/Exception"); 
    if (cls != NULL) { 
     jmethodID constructor = env->GetMethodID(cls, "<init>", "()V"); 
     if(constructor != NULL) { 
      jobject exc = env->NewObject(cls, constructor); 
      if(exc != NULL) { 
       jmethodID printStackTrace = env->GetMethodID(cls, "printStackTrace", "()V"); 
       if(printStackTrace != NULL) { 
        env->CallObjectMethod(exc, printStackTrace); 
       } else { DLOG("err4"); } 
      } else { DLOG("err3"); } 
      env->DeleteLocalRef(exc); 
     } else { DLOG("err2"); } 
    } else { DLOG("err1"); } 
    /* free the local ref */ 
    env->DeleteLocalRef(cls); 
LOGD("###################################################################################printStackTrace}"); 
} 
0

顺便说一句,你是能够引发从原生层一个例外的Java :) 事情是这样的:

jint throwOutOfMemoryError(JNIEnv *env, char *message){ 
    jclass  exClass; 
    char *className = "java/lang/OutOfMemoryError" ; 

    exClass = (*env)->FindClass(env, className); 
    if (exClass == NULL){ 
     return throwNoClassDefError(env, className); 
    } 
    return (*env)->ThrowNew(env, exClass, message); 
} 

或者,如果你有一个Exception的实例,只需将它放入Java层,然后在Java中获取堆栈跟踪。