NDK development cache application

Generation and deletion of global variables, local variables, and weak reference variables

jobject NewGlobalRef(jobject obj)   全局
jobject NewLocalRef(jobject obj)    局部
jobject new WeakGlobalRef(jobject obj)  弱引用

这个方法可以判断对象是否被回收
只需要把obj2变成NULL
jboolean IsSameObeject(jobject obj1, jobject jobj2)

native cache

1.static way

// c++中的缓存方法
extern "C"
JNIEXPORT void JNICALL
Java_com_univer_androidyellowbook_JniDemo_cache(JNIEnv *env, jobject thiz) {
    
    
    // 只被执行一次
    static jfieldID fieldId_string = NULL;
    jclass clazz = env->GetObjectClass(thiz);
    if(fieldId_string == NULL){
    
    
        fieldId_string = env->GetFieldID(clazz, "string", "Ljava/lang/String;");
    }
}

2. The way of global variables

// global variable
jfieldID g_propInt_id = 0;
jfieldID g_propStr_id = 0;

extern "C"
JNIEXPORT void JNICALL
Java_com_univer_androidyellowbook_JniDemo_initNative(JNIEnv *env, jclass clazz) {
    
    
    // TODO: implement initNative()
    g_propInt_id = env->GetFieldID(clazz, "propInt", "I");
    g_propStr_id = env->GetFieldID(clazz, "propStr", "Ljava/lang/String;");
}

In summary, two caching methods are mainly introduced. Because there is no need to consider the problem of memory leakage in C++, we also need to consider whether it can be cached to save some unnecessary memory overhead during development.

Guess you like

Origin blog.csdn.net/esabeny/article/details/112276127