var不会变成全局的,但仍然是本地的 [英] the var doesn't become global but remains local
问题描述
从下面的代码片段中,我尝试测试 NewGlobalRef
并在本地声明它之后尝试使范围
jstring Java_Package_LocalAndGlobalReference_returnGlobalReference
(JNIEnv * env,jobject obj){
if(1){
printf(In function make global reference \\\
);
jclass clsStr;
jclass cls =(* env) - > FindClass(env,java / lang / String);
if(cls == NULL)
return NULL;
//创建一个全局引用clsStr
clsStr =(* env) - > NewGlobalRef(env,cls);
//删除不再有用的本地引用
(* env) - > DeleteLocalRef(env,cls);
if(clsStr == NULL)
return NULL;
}
return clsStr; //语句31
}
当我运行上面的代码片段时,出现以下错误:
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31:错误:'clsStr'未声明(首次在此函数中使用)
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31:错误:(每个未声明的标识符仅被报告一旦
W:\elita\jnitesters\workspace\c\LGR\LGR.c:31:错误:对于它出现的每个函数。)
为什么我得到错误,说我 clsStr
是未定义的使用 clsStr =(* env) - > NewGlobalRef(env,cls)
?
当你在一个块中声明一个变量(在这种情况下,你声明 clsStr $如果
在块之后时它不存在。 if(1){...}
语句),那么该变量的范围(及其生命周期)就是该块。这意味着当<
您可以
$ $前c $ c> clsStr b
$ b
当我使用语句
clsStr =(* env) - > NewGlobalRef(env,cls) code>
这是一个误解 - 你不能通过赋值来创建一个全局变量;你在全球范围内通过声明来做到这一点。你可以通过赋值来初始化一个变量,但这与它的作用域没有任何关系。
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)
?
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 theif(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.
这篇关于var不会变成全局的,但仍然是本地的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!