java JNI 函数是否有可能返回整数或布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27925170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible that JNI function return integer or boolean?
提问by MOHAMED
JAVA Code
爪哇代码
boolean b = invokeNativeFunction();
int i = invokeNativeFunction2();
C code
C代码
jboolean Java_com_any_dom_Eservice_invokeNativeFunction(JNIEnv* env, jobject obj) {
bool bb = 0;
...
return // how can return 'bb' at the end of the function?
}
jint Java_com_any_dom_Eservice_invokeNativeFunction2(JNIEnv* env, jobject obj) {
int rr = 0;
...
return // how can return 'rr' at the end of the function?
}
Is it possible that JNI function return integer or boolean? If yes, How I can do that?
JNI 函数是否有可能返回整数或布尔值?如果是,我该怎么做?
回答by alijandro
Yes, just return the value directly.
是的,直接返回值即可。
JNIEXPORT jint JNICALL Java_com_example_demojni_Sample_intMethod(JNIEnv* env, jobject obj,
jint value) {
return value * value;
}
JNIEXPORT jboolean JNICALL Java_com_example_demojni_Sample_booleanMethod(JNIEnv* env,
jobject obj, jboolean unsignedChar) {
return !unsignedChar;
}
There is a map relation between Java primitive type and native type, reference here.
Java原始类型和原生类型之间存在映射关系,参考这里。
回答by Nathaniel D. Waggoner
I think your method signatures might be wrong...
我认为您的方法签名可能是错误的...
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
If you'll notice a few things:
如果你会注意到一些事情:
1) the addition of JNIEXPORT
and JNICALL
around methods..
2) the to j<object>
type of arguments to be returned.
1) 添加JNIEXPORT
和 JNICALL
环绕方法.. 2)j<object>
要返回的参数类型。
I think you need to mofidy your int example to:
我认为你需要修改你的 int 示例:
JNIEXPORT jint JNICALL Java_com_any_dom_Eservice_invokeNativeFunction2(JNIEnv* env, jobject obj) {
jint rr = 99;
...
return rr;
}
回答by Michael
Why not just do some static casts:
为什么不做一些静态转换:
return static_cast<jboolean>(bb);
return static_cast<jint>(rr);
In my copy of jni.h
jint
is defined as an int32_t
, and jboolean
is defined as a uint8_t
. The internal representations of true
and false
are the same in C++ and Java (at the VM level) AFAIK (i.e. 0==false, 1==true).
在我的副本中jni.h
jint
被定义为int32_t
,并且jboolean
被定义为uint8_t
。的内部表示法true
和false
在C ++和Java相同的(在虚拟机级)AFAIK(即0 ==假,1 == TRUE)。
You can of course add some sanity checks if you want to, e.g.:
如果您愿意,您当然可以添加一些健全性检查,例如:
assert(numeric_limits<jint>::is_signed == numeric_limits<decltype(rr)>::is_signed &&
numeric_limits<jint>::min() <= numeric_limits<decltype(rr)>::min() &&
numeric_limits<jint>::max() >= numeric_limits<decltype(rr)>::max());