Search code examples
javacjava-native-interfaceglobal-variables

the var doesn't become global but remains local


From the following snippet i try to test NewGlobalRef and try to make clsStr global after declaring it in the local scope of if block.

jstring Java_Package_LocalAndGlobalReference_returnGlobalReference
 (JNIEnv *env, jobject obj) {
if(1) {
    printf("In function make global reference\n");
    jclass clsStr ;
    jclass cls = (*env)->FindClass(env,"java/lang/String");
    if( cls == NULL)
        return NULL;
    // create a global reference of clsStr
    clsStr = (*env)->NewGlobalRef(env,cls);
    // Delete the local reference, which is no longer userful
    (*env)->DeleteLocalRef(env,cls);
    if(clsStr == NULL)
        return NULL;
}
 return clsStr; // statement 31
}

When i run the above snippet i get the following errors :

W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: 'clsStr' undeclared (first use in this function)
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: (Each undeclared identifier is reported only once
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31: error: for each function it appears in.)

Why do i get the error saying that clsStr is undefined when i have made that var global using the satement clsStr = (*env)->NewGlobalRef(env,cls) ?


Solution

  • When you declare a variable in a block (in this case, you declare clsStr in the block if the if(1) { ... } statement), the scope of that variable (and its lifetime) is that block. That means it doesn't exist when you return clsStr after the block.

    You can either

    • move the return statement inside the block, or
    • declare the variable clsStr before the if(1) { ... } statement

    when i have made that var global using the statement clsStr = (*env)->NewGlobalRef(env,cls)

    That is a misunderstanding - you can't make a variable global by assignment; you do that by declaration in the global scope. You can initialize a variable by assignment, but that doesn't have anything to do with its scope.